我們需要製作一個詞法分析器,而且我的某個特定函數useLoad或更準確地說,遇到了一些麻煩,發生了什麼在使用useLoad之後的Main中。我看不出爲什麼我的掃描儀在java中拋出一個「NoSuchElementException」
我發現那是因爲...由於某種原因,buffer=keyboard.nextLine()
正在拋出錯誤,因爲由於某種原因它沒有從鍵盤獲得更多輸入。我認爲.nextLine()應該強制它從用戶那裏獲得更多的輸入。我不知道爲什麼在這個特定方法之後拋出異常。它可以完成其他方法,並且不會失去閱讀能力。是否因爲我在另一個對象中有一個名爲鍵盤的變量並將其關閉?這似乎令人懷疑。試圖改變名字。沒有區別。
已使用但未在以下代碼中聲明的變量:關鍵字[0]是字符串「load」。 initial =傳入該函數的掃描器字符串。偏移量=一個計數器變量,用來查看我們讀過的行的距離。
useLoad函數(這是我認爲搞亂了),是在底部,但我包括它運行的所有內容(每個方法分開一個水平的規則),按時間順序,以防萬一我只是沒有看到發生了什麼。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //the scanner for keyboard
int i = 0;
String buffer ="";
boolean loopControl == true;
SymbolTable mySym = new SymbolTable();
System.out.println("READY FOR INPUT\n");
while (loopControl == true){
//read in the line
buffer = "";
buffer = keyboard.nextLine();
if(!mySym.checkStop(buffer)){ //if we didn't stop
mySym.primary(buffer);
}
else{//if we did stop
closeLoop();
}
if (i >= 55){
loopControl = false;
System.out.println(("You have gone over the limit ("+i+" lines) per execution. Please continue by running this program again.").toUpperCase());
//just a safety precaution...you know... in case closeLoop doesn't work
}
i++;
}
keyboard.close();
}
if(initial.substring(0, Keywords[0].length()).equals(Keywords[0])){ //Load
//if this is working as expected, then we simply need to do what the keyword says to do.
offset += Keywords[0].length(); //we have moved this much deeper in to the line
useLoad(offset, initial);
offset = 0; //just make sure, once we are done with the line, we start back at the start of the next line.
return; //we found what we were looking for, get out.
}
private void useLoad(int offsetIn, String readIn) {
double doubIn = 0;
//now get the value of the
Scanner keyboard = new Scanner(System.in); //the scanner for keyboard
System.out.println("\nENTER VALUE FOR " + readIn.toUpperCase());
doubIn = keyboard.nextDouble();
keyboard.close();
variables.create(readIn.substring(offsetIn), doubIn);
}
你在哪裏初始化'loopControl'? – beatrice
'keyboard.close();'關閉鍵盤(duh),所以你不能輸入或讀取任何東西。 (其實這不是很正確,但足夠接近) – immibis
@beatrice它是main類中的全局變量(所以其他方法可能會混淆它,比如closeLoop())。這就是爲什麼它沒有被複制。我忘了那個。我把它作爲局部變量加回來,因爲它沒有太大區別。 –