Reputation: 29
// Write a program that uses a while loop to detect and print multiples of 13 or 17, but not both. Use the exclusive or operator as on page 93.
// The program should start examining integers at 200, and examine successively larger integers until 16 multiples have been detected.
// Correct multiples should be printed right aligned in fields that are 9 characters wide, but with only four multiples per line.
// The total of all correct multiples should be reported after all 16 multiples have been printed.
package Programs5;
public class Program51 {
public static void main(String[] args) {
int main = 200, x = 0, y = 13, z = 17;
while(x < 16) {
main += 1;
if(main % y == 0 ^ main % z == 0) {
x += 1;
System.out.print(main + " ");
}
}
}
}
When I run the program, the logic works and prints each multiple properly. However I need to print four iterations per line. For example:
x x x x
I'm having trouble figuring this one out. I am assuming I need a loop of sorts from my little experience in python but I am just lost at this point.
Upvotes: 3
Views: 120
Reputation: 201439
You forgot to align your fields in nine character wide columns (I would use printf
, and simply add a line break when the count
is a multiple of four). I would start by saving the results of the modulo operations in local variables. Also, you need to keep a running total. Something like,
int count = 0, total = 0, start = 200;
for (; count < 16; start++) {
boolean mod13 = start % 13 == 0, mod17 = start % 17 == 0;
if (mod13 ^ mod17) {
if (count > 0) {
if (count % 4 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
total += start;
System.out.printf("% 9d", start);
count++;
}
}
System.out.printf("%nTotal = %d%n", total);
Outputs
204 208 234 238
247 255 260 272
273 286 289 299
306 312 323 325
Total = 4331
Upvotes: 3