更新时间:2022-02-05 21:12:11
break;
语句可用于……嗯……中断迭代.例如,通过迭代,我的意思是你也可以摆脱 for
.
The break;
statement can be sued to... well... break out of an iteration. And by iteration I mean you can get out of a for
too, for example.
您必须定义何时要中断迭代,然后执行以下操作:
You have to define WHEN do you want to break out of the iteration and then do something like this:
while(Input.hasNextInt(Input)){
if(condition())
break;
count++;
temp = Input.nextInt();
sum += temp;
System.out.println(temp);
System.out.println(count);
}
否则,您可以创建一个辅助方法来定义迭代是否应该继续进行,如下所示:
Otherwise, you can make an auxiliary method that defines if the iteration should keep on going, like this one:
private boolean keepIterating(Scanner in) {
boolean someOtherCondition = //define your value here that must evaluate to false
//when you want to stop looping
return Input.hasNextInt() && someOtherCondition;
}
您必须在 while
中调用的方法:
Method that you will have to invoke in your while
:
while(keepIterating()){
count++;
temp = Input.nextInt();
sum += temp;
System.out.println(temp);
System.out.println(count);
}