【发布时间】:2023-03-15 08:25:01
【问题描述】:
*修正输入扫描
我正在尝试用输入键/空行结束一个while循环
下面的测试代码可以正常工作。
Scanner scan = new Scanner(System.in);
String line;
while ( (line=scan.nextLine()).length() > 0)
{
System.out.println(line);
}
但是,当我将它集成到我的主程序中时(while 循环放置在 do-while 循环中的 int switch case 中),程序会跳过代码 @case2 并继续 do-while 循环
int input;
do{
System.out.print("Choose a function (-1 to exit): ");
input=scan.nextInt();
switch (input)
{
case 1:
break;
case 2:
//same while loop here
break;
}
}while(input!=-1);
示例输出:
Choose a function (-1 to exit): 1
Choose a function (-1 to exit): 2
//skip case2 coding
Choose a function (-1 to exit): 1
Choose a function (-1 to exit): -1
//program ends
【问题讨论】:
-
你能发布你的整个方法体吗?谢谢。
-
是的,尤其是在分配了
input的情况下。 -
你没有在 switch case 中输入任何内容。这会变成无限循环
-
do while 循环应该以
semicolon结束
标签: java while-loop switch-statement blank-line