使用 Java.util.scanner 时出现 noSuchElement 错误 [重复]
Posted
技术标签:
【中文标题】使用 Java.util.scanner 时出现 noSuchElement 错误 [重复]【英文标题】:Error of noSuchElement when using Java.util.scanner [duplicate] 【发布时间】:2018-10-20 16:21:04 【问题描述】:当我在user_Radius.nextLine();
向用户询问他们的半径时出现错误,我目前找不到问题,因为userName1.nextLine();
在我运行程序时工作得很好。
错误
线程“主”java.util.NoSuchElementException 中的异常:没有行 在 java.base/java.util.Scanner.nextLine(Scanner.java:1651) 中找到 CircleFormulas.main(scanner.java:22)
我的代码
import java.util.Scanner;
public class CircleFormulas
public static void main(String[] args)
//Creates my constructors/variables
//Scans for the user's name
Scanner userName1 = new Scanner (System.in);
//Scans for the radius the user wishes to calculate
Scanner user_Radius = new Scanner (System.in);
//Asks the user for their name and places their response into the userName variable
System.out.println("What is your name?: ");
String userName = userName1.nextLine();
//closes the line function; locks the variable
userName1.close();
//Prints out a greeting for the user
System.out.println("Hey " + userName + " How are you?");
//Asks the user a question
System.out.println("Now, what is the radius of the circle you'd like to calculate?");
//Asks the user for their radius they'd like to calculate and places their response into the radius variable
String radius = user_Radius.nextLine();
user_Radius.close();
//Prints out the radius of the user's circle
System.out.println("So, the radius of your circle is: " + radius);
【问题讨论】:
【参考方案1】:您收到错误是因为您尝试重用已关闭的System.in
(即使它在另一个变量中声明,但仍处于关闭状态)。
您不需要实例化多个扫描仪,只需执行一次并多次重复使用即可:
Scanner scanner = new Scanner(System.in);
String userName = scanner.nextLine();
String radius = scanner.nextLine();
scanner.close();
【讨论】:
以上是关于使用 Java.util.scanner 时出现 noSuchElement 错误 [重复]的主要内容,如果未能解决你的问题,请参考以下文章