2012-03-29 85 views
0

我試圖從10個文件中將有符號整數讀入數組中,並且出於某種原因,它沒有發生,並且在編譯和運行時沒有收到任何錯誤。我只是想要第二雙眼睛來看看這個,看看我可能會錯過什麼。Java - 從文件中讀取帶符號整數

測試文件是 「input.txt中」 並且包含:-1,4,32,0,-12,2,30,-1,-3,-32

這是我的代碼:

public void readFromFile(String filename) 
    { 
    try { 
     File f = new File(filename); 
     Scanner scan = new Scanner(f); 
     String nextLine; 
     int[] testAry = new int[10]; 
     int i = 0; 

     while (scan.hasNextInt()) 
     { 
      testAry[i] = scan.nextInt(); 
      i++; 
     } 
    } 
     catch (FileNotFoundException fnf) 
     { 
      System.out.println(fnf.getMessage()); 
     } 
    } 
+0

這是整個程序?對我來說看起來很好....也是testAry是一個局部變量,並且你沒有返回它,所以這個方法究竟做什麼? – 2012-03-29 01:34:09

+0

只讀入輸入到數組中,我需要使用該數組在程序後面的一些其他函數中,會發生什麼情況是在調試模式下,它第一次碰到while語句,並跳過它並從函數中斷開 – seiryuu10 2012-03-29 01:39:29

+0

這是一個本地數組,我沒有看到任何你保存的地方信息在某些地方不是本地的功能,如果這些是逗號,則需要更改Scanner使用的分隔符。 – 2012-03-29 03:03:08

回答

2

嘗試使用分隔符IVE在該行useDelimiter得到(\\ S *,\\ S *「),它的正則表達式用逗號分割你從文件的輸入。


try { 
      File f = new File("input.txt"); 
      Scanner scan = new Scanner(f); 
      scan.useDelimiter("\\s*,\\s*"); 
      String nextLine; //left it in even tho you are not using it 
      int[] testAry = new int[10]; 
      int i = 0; 

      while (scan.hasNextInt()) { 
       testAry[i] = scan.nextInt(); 
       System.out.println(testAry[i]); 
       i++; 
      } 
     } catch (FileNotFoundException fnf) { 
      System.out.println(fnf.getMessage()); 
     } 

0

你可以扔你不要再追了另一個異常

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt()

的int從輸入信息掃描拋出:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range 
NoSuchElementException - if input is exhausted 
IllegalStateException - if this scanner is closed 

或者你可以去老同學,並使用一個緩衝的讀者,以驗證您是您使用的掃描儀對象上默認的分隔符獲取數據

try{ 

    FileInputStream fstream = new FileInputStream(filename); 

    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String strLine; 

    while ((strLine = br.readLine()) != null) { 

    System.out.println (strLine); 
    } 
    in.close(); 
    }catch (Exception e){ 
    System.err.println("Error: " + e.getMessage()); 
    }