【发布时间】:2018-07-30 14:39:45
【问题描述】:
我正在用 Java 编写一个程序,但我遇到了 do-while 循环的问题。我在下面发布了代码,但为了便于阅读,我删除了大部分代码。运行程序时发生的情况是 do-while 循环中的前 4 行打印到屏幕上,然后我输入使用键盘选择的“选项”,最后一行询问我是否要执行另一个动作打印到屏幕上,然后程序就结束了,不允许我输入“是或否”来指示我是否要执行另一个动作。但是,如果我只删除“value = scan.nextInt();”行和“System.out.println(value);”行,那么当我被问及是否要执行另一个操作时,我可以输入“是或否”。
有人明白为什么 do-while 循环不像我在下面写的那样工作吗?
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
String another;
int value;
Scanner scan = new Scanner(System.in);
do
{
System.out.println("Enter the numerical value of one of the following options in order to select an option:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
value = scan.nextInt();
System.out.println(value);
System.out.print("Would you like to perform another action (yes/no)?");
another = scan.nextLine();
}
while (another.equalsIgnoreCase("yes"));
}
}
提前谢谢你。
【问题讨论】:
-
nextInt 不可能消耗 newLine 字符,然后当它读取到另一个变量时,它会读取这个换行符并终止,因为 "\n" 不等于 "yes"跨度>
-
只要使用
scan.next()就可以解决问题了。
标签: java loops java.util.scanner do-while