// 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
我很难弄清楚这个。我假设我需要某种形式的循环,从我的小蟒蛇的经验,但我只是失去了这一点。
答案 0 :(得分:3)
您忘了将字段对齐为9个字符宽的列(我将使用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