英文:
If statement nested in for loop
问题
我正在尝试创建一个程序,如果数字可被2整除,则打印“-”,如果不能,则打印“”。我能够打印数字、-和,但它没有在数字的位置上打印-和*,如果你明白我的意思的话?
public class Exercise2 {
public static void main(String[] args) {
for(int i = 100; i <= 200; i++) {
if(i % 2 == 0){
System.out.println("-");
} else {
System.out.println("*");
}
System.out.println(i);
}
}
}
我不明白我哪里出错了。感谢您提前的帮助。
英文:
I'm trying to create a program that prints "-" if the number is divisible by 2 and "*" if it is not. I get it to print the numbers, - and *, but it is not printing - and * in place of the number, if that makes sense?
public class Exercise2 {
public static void main(String[] args) {
for(int i = 100; i <= 200; i++) {
if(i % 2 == 0){
System.out.println("-");
} else {
System.out.println("*");
}
System.out.println(i);
}
}
}
I can't understand where exactly I'm going wrong. Any help is appreciated and thank you in advance.
答案1
得分: 2
Sure, here's the translated code:
如果您不想打印数字,只需从原始答案中删除 `System.out.println(i);`,然后它应该可以正常工作。
如果您想要在同一行打印符号和数字,可以将 `System.out.println()` 更改为 `System.out.print()`。
public class Exercise2 {
public static void main(String[] args) {
for (int i = 100; i <= 200; i++) {
if (i % 2 == 0) {
System.out.print("- ");
} else {
System.out.print("* ");
}
System.out.println(i);
}
}
}
上面的答案将以以下方式打印数字:
- 100
* 101
- 102
* 103
- 104
* 105
- 106
...
英文:
If you dont want to print the numbers you can just remove System.out.println(i);
from your original answer and it should work fine.
If you want to print the symbol and the number in the same line it can be done by changing the System.out.println()
to System.out.print()
.
public class Exercise2 {
public static void main(String[] args) {
for(int i = 100; i <= 200; i++) {
if(i % 2 == 0){
System.out.print("- ");
} else {
System.out.print("* ");
}
System.out.println(i);
}
}
}
The answer above will print the numbers in this fassion:
- 100
* 101
- 102
* 103
- 104
* 105
- 106
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论