为什么在'for(...)之后添加分号会如此显着地改变我的程序的含义? [英] Why does adding a semicolon after 'for (...)' change the meaning of my program so dramatically?

查看:102
本文介绍了为什么在'for(...)之后添加分号会如此显着地改变我的程序的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下类:

  public class TestOne {
     public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++) {
          count++;
        }
        System.out.println(count);
     }
   }

输出 100

然后我添加了一个分号:

Then I added a semicolon:

    public class TestOne {
     public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++); {     // <-- Added semicolon
          count++;
        }
        System.out.println(count);
     }
   }

输出 1

结果令人难以置信。为什么这个添加的分号会如此显着地改变我的程序的含义?

The result is unbelievable. Why does this added semicolon change the meaning of my program so dramatically?

推荐答案

这不是错误。分号成为主体中循环中唯一的语句。

This is not a bug. The semicolon becomes the only "statement" in the body of your for loop.

写另一种方式来制作更容易看到:

Write this another way to make it easier to see:

for (int i = 0; i < 100; i++)
    ;

{
    count++;
}

计数的块变成一个带有单个语句的裸块,由于分号,它与 for 循环根本没有关联。所以这个块,以及其中的 count ++ 只能执行一次

The block with count++ becomes a bare block with a single statement, which isn't associated with the for loop at all, because of the semicolon. So this block, and the count++ within it, is only executed once.

这是语法上有效的java。 for(int i = 0; i< 100; i ++); 相当于:

This is syntactically valid java. for (int i = 0; i < 100; i++); is equivalent to:

for (int i = 0; i < 100; i++)
{ ; } // no statement in the body of the loop.

for 此表单的循环可能很有用因为循环增量语句或终止条件中的副作用。例如,如果您想编写自己的 indexOfSpace 来查找 String 中空格字符的第一个索引:

for loops of this form can be useful because of the side-effects within the loop increment statement or termination condition. For instance, if you wanted to write your own indexOfSpace to find the first index of a space character in a String:

int idx;

// for loop with no body, just incrementing idx:
for (idx = 0; string.charAt(idx) != ' '; idx++);

// now idx will point to the index of the ' '

这篇关于为什么在'for(...)之后添加分号会如此显着地改变我的程序的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆