【问题标题】:Error of noSuchElement when using Java.util.scanner [duplicate]使用 Java.util.scanner 时出现 noSuchElement 错误 [重复]
【发布时间】: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);
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    您收到错误是因为您尝试重用已关闭的System.in(即使它在另一个变量中声明,但仍处于关闭状态)。

    您不需要实例化多个扫描仪,只需执行一次并多次重复使用即可:

    Scanner scanner = new Scanner(System.in);
    
    String userName = scanner.nextLine();
    String radius = scanner.nextLine();
    
    scanner.close();
    

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多