【发布时间】:2021-04-16 13:46:44
【问题描述】:
while(true)
{
switch (...)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
System.out.println("(1)Continue (2)Exit");
//example:
int choice = scanner.nextInt();
if (choice == 1)
continue; //it should go to switch
else if (choice == 2)
{
System.out.println("Exit..."); // should exit
break;
}
else
{
System.out.println("Wrong num, try it again!"); // should ask choose again until we enter 1 or 2
//goto example;
}
}
我的问题是:当我选择错误的数字时,它会进入循环的开头。我希望它转到询问选择的部分(int selection =scanner.nextInt();)并再次询问。 "1" -> switch, "2" -> "exit" , "3" -> 再次询问选择。
【问题讨论】:
-
把循环放在你想循环的位周围:如果你不想回到开关,要么在开关后移动
while;或者在输入和 if/else 周围放置另一个循环。 -
您永远不需要
goto声明。如前所述:循环正确的事情,然后适当地使用break/continue。