Reputation: 1
Newbie to Java, have an assignment for practice. We are trying to print all values between 1 and 100 that are divisible by 5 or 7. However, there are values that are divisible by 5 AND 7 that will print twice. Simplest way to avoid repeating numbers?
int sum = 0;
i=1;
while (i <= 100)
{
//need to update the value of sum by i
//sum = sum + i;
/*if( i % 5 == 0 || i % 7 ==0 ) //if i is divisible by 5 or 7, let us display i
{
System.out.println(i);
}*/
if ( i % 5 == 0)
{
System.out.println(i);
}
if ( i % 7 == 0)
{
System.out.println(i);
}
if ( i % 5 == 0 || i % 7 == 0)
{
sum = sum + i;
}
//if ( i %
i=i+1;
}
//also print the total of the numbers being displayed
int add;
System.out.println("the sum is: " + sum);
System.out.println("Bye, for now!");
Upvotes: 0
Views: 69
Reputation: 31
Using && operator to print the repeating numbers once and conditional operators to do the rest of the logic will help eventually.
Try this code
int sum = 0;
int i=1;
while (i <= 100)
{
if ( i % 5 == 0 && i % 7 == 0)
{
System.out.println(i);
sum += i;
}
else if ( i % 5 == 0)
{
System.out.println(i);
sum += i;
}
else if ( i % 7 == 0)
{
System.out.println(i);
sum += i;
}
i++;
}
//also print the total of the numbers being displayed
System.out.println("the sum is: " + sum);
System.out.println("Bye, for now!");
Upvotes: 1