2013-04-15 179 views
2

這是我到目前爲止....我想從文件中創建一個使用數據數組

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    final String DATA_FILE = "payroll_problem.txt"; 
     Scanner scan = null; 
     try 
     { 
     scan = new Scanner(new File(DATA_FILE)); 
     } 
     catch (FileNotFoundException e) 
     { 
     System.err.printf("Could not open file \"%s\".\n", DATA_FILE); 
     } 
    int [] arr = new int[scan.nextInt()]; 
    for(int i = 0; i < arr.length; i++) 
    { 
     arr[i] = scan.nextInt(); 
     System.out.print(arr[i]); 
    } 

    scan.close(); 
} 

我不斷收到錯誤代碼

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at fvse.main(fvse.java:22) 

五個整數代表從週一到週五,這個人工作了多少小時。這是數據文件。

Mohnan Maria  8 8 8 9 8 10.01 
Blue Shelly  8 10 8 8 6 10.00 
Black 8 8 8 8 8 23.0 
Fortuna Jorge 5 5 5 5 5 10.10 
Jones Mitchel 10 5.5 10 10 10 15.05 
Olafson Sven 10 10 10 10 10 10.00 
Cruz Astrid 1 1 1 1 1 20.50.3 
Adler Irene 10 12 8 8 8 22.50 
+1

請發佈您的數據文件的一個片段。縮進四個空格,就好像它是代碼一樣,這樣我們就可以看到單獨的行。謝謝! – dasblinkenlight

+0

好的,我發佈了。 – user2280872

回答

0

您正在讀取文件的整數,但很可能是該文件充滿字符串或字符。

編輯:嘗試掃描線或字符,或者只使用一個FileInputStream,然後,一旦它在被加載解析數據

編輯:現在,我已經看到你的數據文件,我會讀該文件使用標準的文件輸入法(如果需要教程,請查看http://www.javapractices.com/topic/TopicAction.do?Id=42)。然後根據空格拆分字符串,並遍歷新字符串數組中的每個字符串並處理數據。前兩個字符串是名稱,然後是整數,直到獲得另一個名稱或字符串的結尾。

1

由於您致電scan.nextInt()而發生此問題,但您的輸入文件實際上包含字符串/字符。

要麼添加一個整數,指示您的輸入文件的頂部線的數量,或者改變您的代碼通過讀取線(如:使用BufferredReader.readLine()

如果選擇前者,請確保您也可以參考使用兩次調用的名字和姓氏scan.next()

相關問題