有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。扫描器Java扫描器找不到行,然后扫描器关闭错误?

我的Java代码要求用户输入,然后将这些数据存储在一个字符串变量中。下面的函数是名为“number”的类的一部分,在主函数中调用

        public static void setVal(int i){

    Scanner readIn = new Scanner(System.in);
    //while (readIn.hasNextLine()){
        str = readIn.nextLine();

        numCheck = false;

        if (i == 1){
            while (!numCheck){

                if (str.contains(" ")){
                    System.out.println("Please input a single item.");
                    str = readIn.nextLine();
                }
                else if (!isNumeric(str)){
                    System.out.println("Please input a valid number.");
                    str = readIn.nextLine();
                }
                else {
                    numCheck = true;
                    value = Double.parseDouble(str);
                    readIn.close();
                }
            }
            readIn.close();
        }

        else if (i == 2){
            while (!numCheck){

                if (str.contains(" ")){
                    System.out.println("Please input a single item.");
                    str = readIn.nextLine();
                }
                else if (!isNumeric(str)){
                    System.out.println("Please input a valid number.");
                    str = readIn.nextLine();
                }
                else {
                    numCheck = true;
                    secondV = Double.parseDouble(str);
                    readIn.close();
                }
            }
            readIn.close();
        }

        else {
            System.out.println("An error has occurred.");
        }
//  }
    readIn.close();
}

部分主要功能如下所示:

     number input = new number();

    for (int i = 1; i <= 2; i++){

        input.setVal(i);

        System.out.println("Now please input a second value for computing with the first.");

        input.setVal(i);

    }

我使用同一个函数两次,但给它一个不同的参数,以区分输入分配给不同的变量,但当它第二次运行时,会抛出一个找不到行的错误

应用您可以看到的其他建议,我添加了一个“hasNextLine()”检查,以在执行代码之前检查该行是否存在,但这最终会导致“Scanner closed”错误,即使每次函数运行时我都会调用Scanner的新实例。我还适当地关闭了扫描仪,以确保误差最小化

我不知道出了什么问题,因为我可以在main函数中创建一个扫描器并调用'。nextLine()'在没有错误的情况下被请求的次数相同,但是当通过类方法再次调用时,我会收到这些错误

感谢您的帮助,提前谢谢


共 (0) 个答案