我有一个基本的控制台应用程序,我只是想在 while 循环中使用一个简单的 Scanner 来捕获用户输入。我试图把standardInput = System.in在build.gradle,但我的程序不阻止时,应等待输入。while (stillWriting) { System.out.println( "Press 1 to write something,\n" + "Press 2 to erase something,\n" + "Press 3 to exit." ); //if you select 1, it goes into the case, but does not block //then ends up here again. int userSelection = scanner.nextInt(); switch (userSelection) { case 1: System.out.println("Enter text to be written: "); //vvvvvv should block here but doesn't. vvvvvv String textToWrite = scanner.nextLine(); paper = pencil.write(paper, textToWrite); break; case 2: //some code break; case 3: stillWriting = false; break; default: System.out.println(userSelection + " is not valid."); break; } }是否有任何替代品或罐子可以使用,使其正确阻塞并实际等待输入?
2 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
您必须消耗<Enter>用户输入的 来做出选择,否则它会(立即)被您的 消耗String textToWrite = scanner.nextLine();:
[...]
int userSelection = scanner.nextInt();
scanner.nextLine(); // <-- consume the <enter>
switch (userSelection) {
[...]
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
事实证明,在每种情况下,您都想接受输入,如果您只是将一个新的 Scanner() 重新分配给扫描仪变量,它将正确地阻塞。
尽管如此,仍然不会选择换行符。
添加回答
举报
0/150
提交
取消