3

我正在使用 foreach 循环遍历 arraylist 并将名称与字符串进行比较。但我不知道为什么当我将名称与字符串进行比较时,它总是会打印出来。

for (Picture item : collection) {


                System.out.println("This is the label " + item.getName());

                if (item.getName().equals("This shouldn't work")); {

                System.out.println("Why is this working");

                }
            }
        }

输出

getting the name test A 
This is the label A
getting the name test A
Why is this working
getting the name test B
This is the label B
getting the name test B
Why is this working
4

3 回答 3

4

分号表示语句的结束,它是块的组成部分。通过键入

if (condition);
{ 
  System.out.println("Why is this working");
}

你在表明

if (condition)
  // empty statement
;
{ // unconditional opening of a block scope
  System.out.println("Why is this working");
}

因此,如果您的if语句评估为 true,则不会发生任何事情,如果评估为 false,则将跳过空语句,这相当于什么也没发生。

现在,如果您删除了该分号,那么下一个“语句”将是块作用域的开头:

if (condition) { 
  // conditional opening of a block scope
  System.out.println("Why is this working");
}

并且您会看到预期的行为,当条件为假时,会跳过“为什么这是有效的”作为输出。

于 2013-10-15T15:13:33.417 回答
1

if (item.getName().equals("This shouldn't work"));//这里有分号

您的代码应如下所示

if (item.getName().equals("This shouldn't work")){

 }
于 2013-10-15T15:12:39.547 回答
0

改变

if (item.getName().equals("This shouldn't work")); {

if (item.getName().equals("This shouldn't work")) {

如果你把分号放在if语句结束

于 2013-10-15T15:13:23.680 回答