2014-01-23 133 views
0

我在閱讀和存儲文本文件中的整數時遇到問題。我正在使用一個int數組,所以我想在沒有列表的情況下執行此操作。我收到一個輸入不匹配異常,我不知道該如何解決這個問題。正在讀取的文本文件也包含字符串。從txt文件讀取整數並存儲到數組中

public static Integer[] readFileReturnIntegers(String filename) { 
    Integer[] array = new Integer[1000]; 
    int i = 0; 
    //connect to the file 
    File file = new File(filename); 
    Scanner inputFile = null; 
    try { 
     inputFile = new Scanner(file); 
    } 
    //If file not found-error message 
     catch (FileNotFoundException Exception) { 
      System.out.println("File not found!"); 
     } 
    //if connected, read file 
    if(inputFile != null){   
     System.out.print("number of integers in file \"" 
       + filename + "\" = \n"); 
     //loop through file for integers and store in array  
     while (inputFile.hasNext()) { 
      array[i] = inputFile.nextInt(); 
      i++; 
     } 
     inputFile.close(); 
    } 
    return array; 
    } 
+1

發表您的文本文件的內容... – gowtham

+0

檢查'next()'[isNumeric](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric%28java.lang.CharSequence %29) –

+0

'hasNextInt()'when using nextInt()'.. – 2014-01-23 06:06:12

回答

2

你可能會使用類似的東西(跳過任何非int),你應該關閉你的Scanner

// if connected, read file 
if (inputFile != null) { 
    System.out.print("number of integers in file \"" 
     + filename + "\" = \n"); 
    // loop through file for integers and store in array 
    try { 
    while (inputFile.hasNext()) { 
     if (inputFile.hasNextInt()) { 
     array[i] = inputFile.nextInt(); 
     i++; 
     } else { 
     inputFile.next(); 
     } 
    } 
    } finally { 
    inputFile.close(); 
    } 
    // I think you wanted to print it. 
    System.out.println(i); 
    for (int v = 0; v < i; v++) { 
    System.out.printf("array[%d] = %d\n", v, array[v]); 
    } 
} 
+0

Wooh似乎已經做到了!如果我打印出每個整數,我是否要使用for循環? –

+0

@ Asiax3我編輯了這55分鐘前...看看'printf'這一行。 –

+0

哦,謝謝你的Elliott!但不幸的是,我在做我的程序全錯了:(我需要通過hasNextLine()方法遍歷文件,使用try和catch來確定哪些詞是整數,哪些不是使用InputMismatchException。提交另一個問題,因爲我問這個不正確的幫助:(。 –

2

變化hasNext()hasNextInt()在while循環。

+0

我試過這個,當試圖打印出其中一個整數時,我得到了空值。 –

+0

@ Asiax3要循環遍歷非整數,您需要將其包裝在另一個hasNext()while循環中,並在hasNextInt()while循環下使用next()。這與艾略特所說的實際上是一樣的。 – Didericis

0

你需要做的就是你得到一個新的價值,並試圖把它變成你需要檢查,以確保它實際上是一個int數組之前,如果沒有則跳過它並轉到下一個值。或者,您可以創建所有值的字符串數組,然後僅將整數複製到單獨的數組中。但是,第一種解決方案可能是兩者中較好的一種。

而且......正如在它往往是更容易爲字符串讀取整數,然後從中解析值的評論提到...

相關問題