2016-11-10 20 views
0

嗨我想通過使用掃描儀讀取input.txt文件,但我不斷收到輸入不匹配異常,我不確定爲什麼。我正在閱讀的文件格式如下:首先是用於識別數組大小的單個數字。下一行是用逗號分隔的整數列表。這是我有什麼,但它的第一個整數無法被讀取:Java使用掃描儀時出現MisMatchException,但爲什麼?

 File inputFile = new File("input.txt"); 
    Scanner scan = new Scanner(inputFile); 
    int arraySize = scan.nextInt(); 
    scan.nextLine(); 
    int[] array = new int[arraySize]; 
    for (int i = 0; i < arraySize; i++) { 
     array[i] = scan.nextInt(); 
    } 

我也認爲我可能會需要有什麼每個INT後趕上逗號。也許scan.next(「,」)?但它在第一個逗號前失敗。

在此先感謝!

編輯:輸入例如文件:

5 
-1, -2, -3 , -4, -5 
+0

你能後的輸入文件,或者至少開始?有關逗號,請參見[如何在Java中分割字符串](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java)。 – bradimus

+0

快速修復會在您的'scan.nextLine'後面使用'scan.useDelimeter(「,」)',它應該忽略逗號並在獲取下一個輸入時使用每個int – Zircon

+0

我發佈了示例輸入文件,但調試顯示錯誤發生在第一個逗號之前,我在逗號分隔符中添加並且仍然沒有傳遞第一個值。 – user6287161

回答

0
File inputFile = new File("C:\\file.txt"); 
    Scanner scan = new Scanner(inputFile); 
    String size = scan.nextLine(); // read size 
    String aux = scan.nextLine(); 
    aux = aux.replaceAll("\\s",""); // remove whitespaces for better Integer.parseInt(String) 
    String[] parts = aux.split(","); 
    System.out.println("size "+size); 
    for (int i = 0; i < parts.length; i++) { 
     System.out.println(parts[i]); 
    } 
    scan.close(); 

然後您可以將字符串轉換爲整數。

0

你的問題是調用scanner.nextInt()用空格分隔元素。有兩件事可以解決這個問題:您可以將分隔符設置爲「,」(scanner.useDelimiter(", ");)或查看Oscar M的答案。
例子:

Scanner sc = new Scanner("-1, -2, -3, -4"); 
sc.useDelimiter(", "); 
System.out.println(sc.nextInt()); 
System.out.println(sc.nextInt()); 

輸出:

-1 
-2 
+0

即使這樣做是出於某種原因,當我= 2時,它給了我同樣的錯誤。我只是不明白它是如何工作的前幾個,但沒有休息。這是否與偶然的負面信號有關? – user6287161

+0

確保您使用的逗號字符是文件中的逗號字符。 –

0

你需要指定你讀的字符串分隔符。它默認只使用空白而不是逗號。

public static void main (String[] args) 
{ 
    int size = 5; 
    Scanner sc = new Scanner("-1, -2, -3, -4, -5"); 
    sc.useDelimiter("\\s*,\\s*"); // commas surrounded by whitespace 
    for (int i = 0; i < size; i++) { 
     System.out.println(sc.nextInt()); 
    } 
} 

Example