你好,我正在编写一个代码,它将在第 10 个数字之后打印偶数整数,它将在新行上开始,因此每列 10 行有 10 个数字。我的代码正在打印所有数字,但我希望它只打印偶数我尝试使用 if 语句,但它似乎不起作用,请帮忙。下面是我的代码。
public static void mjj() {
int s = 1;
for (int i = 1; i <=10;i++) {
for (int j = 1; j <=10;j++) {
if (s % 2 == 0)
System.out.print(s++ + " ");
}
System.out.println();
}
}
输出
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
我希望它打印这个
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
依此类推,直到第10行
最佳答案
发布的代码不会打印任何内容,因为 s
永远不会改变。
您可以通过将 s
的增量移动到 if
之前来修复此问题:
public static void mjj() {
int s = 1;
for (int i = 1; i <=10;i++) {
for (int j = 1; j <=10;j++) {
s++; // <-- do it here
if (s % 2 == 0)
System.out.print(s + " ");
}
System.out.println();
}
}
输出
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
52 54 56 58 60
62 64 66 68 70
72 74 76 78 80
82 84 86 88 90
92 94 96 98 100
如果您希望每行有 10 个数字,请修改 for 循环:
public static void mjj() {
int s = 1;
for (int i = 1; i <= 5;i++) { // up to 5
for (int j = 1; j <=20; j++) { // up to 20
s++; // <-- do it here
if (s % 2 == 0)
System.out.print(s + " ");
}
System.out.println();
}
}
或者让它更简单一点:
public static void mjj() {
for (int j = 2; j <=100; j += 2) {
System.out.print(j + " ");
if (j % 20 == 0)
System.out.println();
}
}
输出
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
关于java - 嵌套for循环偶数打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46901771/