我想讓掃描儀讀取文本文件的輸入,將該輸入放入字符串,使用該字符串的StringTokenizer,然後在該字符串的每個元素上都有一個String []數組是StringTokenizer的一個標記。這樣做的目的是從文本文件中獲取輸入文本的String [],以便數組的每個元素都是文本文件中的一個詞。然而,我迄今爲止的代碼會生成一個NoSuchElementFound異常。使用掃描儀獲取NoSuchElement發現
Scanner f = new Scanner( "input.txt"); // Yes, I have the file path here, I changed it though.
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt");
String temp = "";
String cString = "";
while((cString = f.nextLine()) != null) { // Line where exception occurs
temp += cString;
}
StringTokenizer everythingTokens = new StringTokenizer(temp);
String[] everything = new String[ everythingTokens.countTokens() ];
for(int i = 0; i < everything.length; i++) {
everything[ i ] = everythingTokens.nextToken();
}
out.println(everything[ 0 ]);
以下是錯誤消息
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at gift1.main(gift1.java:21)
Java Result: 1
在文本文件中查找該輸入是
Hey,
How are you?
這究竟是爲什麼以及如何解決呢?