使用 Java - 每 9 个字符宽的行打印四次迭代


// 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 + " ");
}
}
}
}

当我运行程序时,逻辑工作并正确打印每个倍数。但是我需要每行打印四次迭代。例如:

x x x x

我很难弄清楚这一点。我假设我需要从我在 python 方面的一点经验中得到一个循环,但我现在只是迷失了。

您忘记将字段对齐到九个字符宽的列中(我会使用printf,并在count是 4 的倍数时简单地添加一个换行符(。我将首先将模运算的结果保存在局部变量中。此外,您需要保持运行总计。像这样,

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);

输出

204       208       234       238
247       255       260       272
273       286       289       299
306       312       323       325
Total = 4331

最新更新