【问题标题】:Looping never happens while the condition is never being satisfied?永远不会满足条件时不会发生循环?
【发布时间】:2018-05-01 06:46:41
【问题描述】:

感谢000的建议,但我还是个新手,想知道这个结果背后的概念。任何人都可以明确表示?

0hi
3hello
3world

而不是

0hi
0hello
0world

(假设:num 永远不会是 ++,因为值是 0。)

application.args=hi hello world

public static void main (String[] args){
    int num;
    num=0;

    for (String s:args) {
        System.out.println(num+s);
        for(num=0;2>=num;num++);
    }

}

【问题讨论】:

  • 嗯,你觉得你在这里做什么:for(num=0;2>=num;num++); ?

标签: java loops for-loop arguments conditional-statements


【解决方案1】:

如果你想用它打印所有参数和数字,那么修改你的循环就像

for (String s:args){
System.out.println(num + " " + s);
num++;  // don't write this if you want 0 as the number every time
}

编辑 如果您想知道为什么代码中的 num 会增加到 3,那么

  • 控件先到for(String s: args)

  • 然后将args的第一个值(0索引处的值)复制到s中

  • 然后它点击System.out.println(num+s); 打印仍然为零的num 值和s 值

  • 现在for(num=0;2>=num;num++); 它将增加 num 直到 num ≤= 2 所以在 for 语句执行后你的 num 值变为 3

  • 然后进行第二次外循环迭代,将 args 的第二个值复制到 s 中

  • 然后将 num(即 3) 与 s 一起打印,这将重复,直到 args 中的所有值都没有被处理

【讨论】:

    【解决方案2】:

    试试这个代码,你想要的输出:0hi 0hello 0world

        int num = 0;
        for (String s : args) {
            //To get array of words data[0] = "hi", data[1] = "hello", data[2] = "world"
            String[] data = s.split(" ");
            //Loop through all words
            for (String element : data) {
                System.out.println(num + element);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 2013-11-22
      • 2012-02-21
      • 2020-02-03
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多