使用扫描仪时出现NoSuchElement异常

NoSuchElement exception when using Scanner(使用扫描仪时出现NoSuchElement异常)

本文介绍了使用扫描仪时出现NoSuchElement异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在程序中使用Scanner第二次从控制台获取输入,但在调用另一个方法中的第二个Scanner时,出现了NoSuchElement异常。

如果我从运行startMenu()中删除startMenu(),它会正常运行,但由于某种原因,在运行后它会抛出异常。

    public class Garden {
    public static final Garden GARDEN = new Garden();
    //variable declartaions removed
    public static void main(String[] args) {
        if (null != args && 0 < args.length) {
            GARDEN.fileName = args[0].trim();
        }
        if (GARDEN.fileName != null) {
            GARDEN.fileReader(GARDEN.fileName);
        } else {
            GARDEN.fileReader();
        }

        GARDEN.startMenu();
        int mainI = 0;
        while (mainI != 1000000) {
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
            }
            GARDEN.daysWeather();
            GARDEN.anotherDay();
            mainI++;
        }
    }


    protected void fileReader() { // asks for file name for config file
        System.out.println("Enter File Name Please");
        Scanner cmdReader = null;
        String cmdInput = null;
        try {
            cmdReader = new Scanner(System.in);
            cmdInput = cmdReader.nextLine();
        } catch (NoSuchElementException noSuchElement) {
            noSuchElement.printStackTrace();
            fileReader();  //throwing error here
        }

        //code removed
    }



    protected void startMenu() {// modified code from ATM lab (week2)
    int selected = 0;
        //code removed 
        Scanner climateScanner = new Scanner(System.in);
        System.out.println("Select a number 1-4");
        selected = climateScanner.nextInt();
        switch (selected) {
        case 1: // semiarid
            weatherType = 10; //10% chance to rain
            climateScanner.close();
            break;
        case 2: // arid
            weatherType = 20; //5% chance to rain
            climateScanner.close();
            break;
        case 3:
            weatherType = 50; //2% chance to rain
            tropicalWeather = true;
            climateScanner.close(); 
            break;
        case 4:
            weatherType = 20;//5% chance to rain 
            storming = true;
            climateScanner.close();
            break;
        default:
            System.out.println("Invalid Input try again");
            startMenu(); //using Recursion to ask for input again
            break;
        }
        //code removed
    }
}

推荐答案

 GARDEN.startMenu();// method id not a static one.

您不能以这种方式访问它。您必须初始化类或使您的方法成为静态方法。什么是GARDEN

确定,您现在可以编辑代码了。

再次

 GARDEN.fileReader(GARDEN.fileName); // you are parsing input argument 
                                // But method in your class is no argument method

这篇关于使用扫描仪时出现NoSuchElement异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用扫描仪时出现NoSuchElement异常

基础教程推荐