当我向用户询问他们在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);
}
}
答案 0 :(得分:1)
出现错误是因为尝试重用已关闭的System.in
(即使在另一个变量中声明了该变量,但仍处于关闭状态)。
您无需实例化多个扫描仪,一次执行并多次重复使用就足够了:
Scanner scanner = new Scanner(System.in);
String userName = scanner.nextLine();
String radius = scanner.nextLine();
scanner.close();