Use Java – Print four iterations per 9-character wide line… here is a solution to the problem.
Use Java – Print four iterations per 9-character wide line
// 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 correctly. But I need to print four iterations per line. For example:
x x x x
I’m having a hard time figuring this out. Based on my experience with python, I’m assuming I need some kind of loop, but at this point I’m just getting lost.
Solution
You forgot to align your fields in a nine-character wide column (I’ll use printf
and simply add a newline character when count
is a multiple of four). I will start by saving the results of the modulo operation in local variables. Also, you need to keep the totals. Something like that,
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);
Output
204 208 234 238
247 255 260 272
273 286 289 299
306 312 323 325
Total = 4331