即使代碼編譯:我應該怎麼做才能解決這個掃描儀相關的錯誤?
import java.util.Scanner; // imports the Scanner class from the java.util package
public class ScannerPractice {
public static void main(String args[]) {
Scanner word = new Scanner("word 1 2 3 4"); // creates a new Scanner objecrt with a string as its input
String scaStr = word.nextLine(); // converts scanner to string
String strArr[] = new String[10];
// as long as the scanner has another character...
for (int i = 0; i < scaStr.length(); i++) {
int j = 0;
String k = "";
// if the next token is an integer...
if (word.hasNextInt()) {
j = word.nextInt();
k = String.valueOf(j);
strArr[i] = k;
}
// otherwise, skip over that token
else {
word.next();
}
}
String k = "";
// for each character in charArr
for (int i = 0; i < strArr.length; i++) {
// Accumulate each element of charArr to k
k += " " + strArr[i];
}
System.out.print(k);
}
}
我得到這個錯誤:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ScannerPractice.main(ScannerPractice.java:28)
的異常是指第28行,這就是:
word.next();
我已經試過看着我for循環將值賦給字符串數組,但我仍然找不到錯誤。
我正在試圖解決這個問題。即使是一個暗示,將不勝感激。
根據文檔,掃描程序拋出,如果你調用'next()'並且沒有更多的標記可用。而且,他們不可用,因爲他們還沒有打字,我想。 –
你的代碼沒有任何意義,因爲你創建了一個可以處理令牌的掃描器,但是然後遍歷一個扁平的字符串。那麼,你想使用掃描儀或使用常規字符串進行標記嗎? –
想一想,如果你爲你的循環使用'scaStr.length()',你會經歷多少次迭代。如果你真的只是試圖解析你的字符串中的所有內容,那麼你可以使用'word.hasNextInt()'來確定你是否想繼續前進。 – Dana