2012-07-23 56 views
2

我想讓掃描儀讀取文本文件的輸入,將該輸入放入字符串,使用該字符串的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? 

這究竟是爲什麼以及如何解決呢?

回答

2

這不是你如何使用掃描儀。你會做,而不是:

while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 
    // work with your line here 
} 

請看看在Scanner API,你會看到,它沒有返回null如果它運行線。相反,它會拋出一個.... NoSuchElementException。我認爲你把它和BufferedReader的使用混淆了,它們確實是兩個完全不同的物種。

1

切換到這一點 -

while(f.hasNextLine()) { 
    cString = f.nextLine(); 
    temp += cString; 
}