本文介紹了使用掃描儀時出現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異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,