如果语句嵌套在for循环中

huangapple go评论60阅读模式
英文:

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 &lt;= 200; i++) {
            if(i % 2 == 0){
                System.out.println(&quot;-&quot;);
            } else {
                System.out.println(&quot;*&quot;);
            }
            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 &lt;= 200; i++) {
            if(i % 2 == 0){
                System.out.print(&quot;- &quot;);
            } else {
                System.out.print(&quot;* &quot;);
            }
            System.out.println(i);
        }
    }
}

The answer above will print the numbers in this fassion:

- 100
* 101
- 102
* 103
- 104
* 105
- 106
...

huangapple
  • 本文由 发表于 2020年8月12日 21:51:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63378009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定