gpt4 book ai didi

java - 使用 Scanner 时出现 NoSuchElement 异常

转载 作者:行者123 更新时间:2023-12-01 13:43:26 27 4
gpt4 key购买 nike

我试图在程序中使用 Scanner 再次从控制台获取输入,但是当在另一种方法中调用第二个 Scanner 时,它会出现 NoSuchElement异常(exception)。

如果我从运行 fileReader() 中删除 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

关于java - 使用 Scanner 时出现 NoSuchElement 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com