提问人:sakshi 提问时间:10/7/2022 更新时间:10/7/2022 访问量:56
java.util.NoSuchElementException:未找到带有字符串输入的错误 java
java.util.NoSuchElementException: No line found error java with string input
问:
第一个 int 扫描器工作并按预期输出“输入要推送到堆栈的字符串”,但强扫描器不起作用。一旦用户为第一个扫描仪按回车键,并且打印了第一个字符串,它就会立即抛出 NoSuchElementException,我该如何接受用户的输入?
while (true) {
System.out.println("1. Place string on stack"
+ "\n"
+ "2. Remove top string on stack"
+ "\n"
+ "3. Examine top string on stack"
+ "\n"
+ "4. See if stack is empty"
+ "\n"
+ "5. Find size of stack"
+ "\n"
+ "0. Quit");
Scanner userInput = new Scanner(System.in); // Create a Scanner object
int input = userInput.nextInt();
userInput.close();
switch(input) {
//user quits program
case 0: System.exit(0);
break;
//user wants to place a string on the stack
case 1:
Scanner userInputString = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter string to be pushed onto stack");
String userString = userInputString.nextLine();
userInputString.close();
stack.push(userString);
System.out.println(userString + " has been pushed onto the stack");
break;
}}
答:
0赞
Dennis LLopis
10/7/2022
#1
不知道为什么要创建多个扫描仪并将它们关闭在 while 循环中。在 while 循环之外创建一个扫描仪供用户输入,并确保在用户输入“0”时将其关闭。
userInput.nextInt() 不会使用回车符,而是会保留在扫描器中,直到您使用 userInput.nextLine() 使用它为止;
int input = userInput.nextInt();
userInput.nextLine(); // consumes the carriage return from scanner
还可以在扫描程序中分析整数值。
int input = Integer.parseInt(userInput.nextLine());
稍微修改了您的代码:
Scanner userInput = new Scanner(System.in); // Create one Scanner object
boolean running = true;
Stack<String> stack = new Stack<>();
while (running) {
System.out.println("1. Place string on stack"
+ "\n"
+ "2. Remove top string on stack"
+ "\n"
+ "3. Examine top string on stack"
+ "\n"
+ "4. See if stack is empty"
+ "\n"
+ "5. Find size of stack"
+ "\n"
+ "0. Quit");
/* int input = Integer.parseInt(userInput.nextLine()); // Parse the integer value*/
int input = userInput.nextInt(); // doesn't consume the carriage return
userInput.nextLine(); // Consume the next line in scanner to clear the carriage return
switch(input) {
case 0: {
userInput.close();
System.out.println("Terminating program");
running = false;
break;
}
case 1 : {
System.out.println("Enter string to be pushed onto stack");
String userString = userInput.nextLine();
stack.push(userString);
System.out.println(userString + " has been pushed onto the stack");
break;
}
default : break;
}
}
userInput.close(); // close your resources
评论
Integer.parseInt(userInput.nextLine())
Scanner