Java Scanner.nextLine()不等待输入
我以前有几种方法用于接受用户输入,并将其作为某种数据类型返回给调用它的方法。我在以前的项目中使用过这些方法或它们的变体。
我采用了用于字符串的方法来选择给定的第一个字符并返回它,以便可以在菜单中使用它。每次我启动该应用程序时,都会出现主菜单,并等待用户输入。收到此输入后,程序将连续循环直到停止。这是我捕获字符的方法:
private char getUserChar(String prompt) { try {
Scanner scan = new Scanner(System.in);
System.out.print(prompt);
String tempString = "";
tempString = scan.nextLine();
scan.close();
char userChar = tempString.charAt(0);
return userChar;
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
return 0;
}
由于try /
catch块,代码循环,因为scan.nextLine()永远不会等待下一个输入。没有它,异常通常与找不到新行有关。我尝试了while(scan.hasNextLine())似乎对其他人有用的方法;但是,一旦输入时间到了,它就永远不会中断。我也不相信我会遇到每个人似乎都遇到麻烦的nextInt()问题。我将在下面发布整个课程的代码:
import java.util.Scanner;import controller.Controller;
public class TUI {
private Controller controller;
public TUI() {
Controller controller = new Controller();
this.controller = controller;
}
public void run() {
boolean wantToQuit = false;
char userInput = 0;
System.out.println("Welcome to the Mart.");
do{
userInput = mainMenu();
if(isUserInputValid(userInput))
switch(userInput){
case 'a': addItem();
break;
case 'r': controller.removeItem();
break;
case 'i': controller.printInventory();
break;
case 'p': controller.customerPurchase();
break;
case 'w': controller.weeklyStock();
break;
case 'c': wantToQuit = true;
break;
}
else System.out.println("\nMainMenu");
} while(!(wantToQuit));
System.out.println("WolfMart is now closed. Thank you and good-bye.");
}
private boolean isUserInputValid(char userInput) {
char[] testSet = {'a', 'r', 'i', 'p', 'c', 'w'};
for(char currentChar : testSet) {
if(currentChar == userInput)
return true;
}
return false;
}
private char mainMenu() {
System.out.println();
controller.printInventory();
String mainMenuSelection = "What would you like to do: (a)dd item, (r)emove item, print (i)nventory, " +
"(p)urchase by customer, (c)lose store?\r\n";
char mainMenuInput = getUserChar(mainMenuSelection);
return mainMenuInput;
}
private char getUserChar(String prompt) {
try {
Scanner scan = new Scanner(System.in);
System.out.print(prompt);
String tempString = "";
tempString = scan.nextLine();
scan.close();
char userChar = tempString.charAt(0);
return userChar;
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
return 0;
}
private int getUserInt(String prompt) {
Scanner scan = new Scanner(System.in);
int userInt = -1;
try {
System.out.print(prompt);
String input = scan.nextLine();
userInt = Integer.parseInt(input);
}
catch(NumberFormatException nfe) {
System.out.println("I did not recognize your command, please try again.");
}
scan.close();
return userInt;
}
private String getUserString(String prompt) {
Scanner scan = new Scanner(System.in);
String userString = null;
try{
System.out.print(prompt);
userString = scan.nextLine();
} catch(Exception ex)
{
System.out.println("I did not recognize your command, please try again.");
}
scan.close();
return userString;
}
private double getUserDouble(String prompt) {
Scanner scan = new Scanner(System.in);
double userDouble = -1.0;
try {
System.out.print(prompt);
String input = scan.nextLine();
userDouble = Double.parseDouble(input);
}
catch(NumberFormatException nfe) {
System.out.println("I did not recognize your command, please try again.");
}
scan.close();
return userDouble;
}
private void addItem() {
String itemName = "";
double price;
int quantity;
String namePrompt = "Enter the name of the item being added to the inventory: ";
String pricePrompt = "Enter the cost of " + itemName + ": ";
String quantityPrompt = "Enter the quantity of " + itemName + ": ";
itemName = getUserString(namePrompt);
price = getUserDouble(pricePrompt);
quantity = getUserInt(quantityPrompt);
controller.addItem(itemName, quantity, price);
}
}
回答:
正如我在评论中所述,问题是
:
Scanner scan = new Scanner(System.in);...
scan.close();
现在,看一下
Scanner.nextLine
:
NoSuchElementException
-如果找不到行IllegalStateException
-如果关闭此扫描仪
现在,由于扫描仪 本身 未关闭,IllegalStateException
因此不会抛出。相反,如前所述,将引发另一个异常,“
通常与找不到新行有关 ”- NoSuchElementException
。
假设您正在使用JDK
7,可以通过检查Scanner.throwFor
以下内容来了解其工作原理:
if ((sourceClosed) && (position == buf.limit())) throw new NoSuchElementException();
由于引发了异常,因此将0
返回的值,getUserChar
然后将其用于run
循环中:
do { userInput = mainMenu();
if (isUserInputValid(userInput)) {
...
} else {
System.out.println("\nMainMenu");
}
} while (!wantToQuit);
由于输入无效,您将陷入循环打印之中"\nMainMenu\n"
。
若要更正此问题,请尝试使用一个Scanner
并且不要关闭System.in
;-)
以上是 Java Scanner.nextLine()不等待输入 的全部内容, 来源链接: utcz.com/qa/418710.html