我在while循环中有很多if语句,程序必须根据条件打印错误消息,但如果有多个错误,则必须只有其中一个。
答案 0 :(得分:6)
你的问题不是很详细,所以有点难以确定你想要什么。
如果你希望while循环在任何错误触发后进入下一次迭代,你应该使用continue
语句:
while( something )
{
if( condition )
{
//do stuff
continue;
}
else if( condition 2 )
{
//do other stuff
continue;
}
<...>
}
如果这些if
s不在循环内,并且条件是整数值,则应考虑使用switch
代替:
while( condition )
{
switch( errorCode )
{
case 1:
//do stuff;
break;
case 2:
//do other stuff;
break;
<...>
}
}
如果你想彻底重新启动循环......那么这有点困难。由于您有一个while
循环,您可以将条件设置为它的起始值。例如,如果您有这样的循环:
int i = 0;
while( i < something )
{
//do your stuff
i++;
}
然后你可以像这样“重置”它:
int i = 0;
while( i < something )
{
//do your stuff
if( something that tells you to restart the loop )
{
i = 0;//setting the conditional variable to the starting value
continue;//and going to the next iteration to "restart" the loop
}
}
但是,你应该非常小心,很容易意外地获得无限循环。
答案 1 :(得分:-1)
String errorMessage = "No Error";
while( cond){
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
}
如果您想在遇到任何错误后中断,请使用break
如果要在遇到任何错误后忽略当前迭代,请使用continue
如果要在遇到任何错误后终止执行,请使用exit