2017-02-09 72 views
-1

即使代碼編譯:我應該怎麼做才能解決這個掃描儀相關的錯誤?

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循環將值賦給字符串數組,但我仍然找不到錯誤。

我正在試圖解決這個問題。即使是一個暗示,將不勝感激。

+0

根據文檔,掃描程序拋出,如果你調用'next()'並且沒有更多的標記可用。而且,他們不可用,因爲他們還沒有打字,我想。 –

+0

你的代碼沒有任何意義,因爲你創建了一個可以處理令牌的掃描器,但是然後遍歷一個扁平的字符串。那麼,你想使用掃描儀或使用常規字符串進行標記嗎? –

+0

想一想,如果你爲你的循環使用'scaStr.length()',你會經歷多少次迭代。如果你真的只是試圖解析你的字符串中的所有內容,那麼你可以使用'word.hasNextInt()'來確定你是否想繼續前進。 – Dana

回答

1

您已經使用了此行上Scanner中的所有字符串。

String scaStr = word.nextLine();

因此,掃描儀沒有更多characteres,這就是爲什麼你得到這個錯誤。

我認爲你不需要'將掃描器轉換爲字符串'來迭代它。您可以簡單地使用while來檢查您的Scanner是否有剩餘的字符。

while(word.hasNext()) { 
    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(); 
    } 
} 
0

改變循環檢查掃描儀是否有更多的輸入:

Scanner word = new Scanner("word 1 2 3 4"); 
String strArr[] = new String[10]; 
int i = 0; 

while (word.hasNext()) { 
    int j = 0; 
    String k = ""; 

    if (word.hasNextInt()) { 
     j = word.nextInt(); 
     k = String.valueOf(j); 
     strArr[i] = k; 
    } 
    else { 
     word.next(); 
    } 
} 

它沒有意義遍歷你已經從掃描儀所消耗的字符串,因爲這樣你失去匹配令牌的能力。如果你想使用字符串標記器,你可以這樣做,但是你可以使用掃描器。

0

如果你希望你的代碼正常運行輸入更改爲:

Scanner word = new Scanner("word"+"\n"+"1"+"\n"+"2"+"\n"+"3"+"\n"+"4"); 

添加換行符解決了這個問題。

相關問題