2014-01-23 53 views
0

我一直在這個程序上整天都有壓力問題來讀取整數的文本文件並將整數存儲到數組中。我以爲我終於用下面的代碼得到了解決方案。我不得不通過hasNextLine()方法遍歷文件。 然後使用nextInt()從文件讀取整數並將它們存儲到數組中。 所以使用掃描器構造函數,hasNextLine(),next()和nextInt()方法。從文本文件中讀取整數並存儲到數組中

然後使用嘗試並捕獲以確定哪些詞是整數,哪些不是使用InputMismatchException。文件中的空白行也是例外情況? 問題是我沒有使用try和catch和exceptions,因爲我剛剛跳過了非ints。 此外,我正在使用一個int數組,所以我想這樣做沒有列表。

 public static void main(String[] commandlineArgument) { 
     Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]); 
     ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]); 
     } 

     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) { 
     // 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(); 
      } 
      System.out.println(i); 
      for (int v = 0; v < i; v++) { 
       System.out.println(array[v]); 
      } 
     } 
     return array; 
     } 

     public static void printArrayAndIntegerCount(Integer[] array, String filename) { 
     //print number of integers 
     //print all integers that are stored in array 
     } 
    } 

然後,我會在我的第二種方法中打印所有內容,但我可以在後面擔心。 :○文本文件的

實施例的內容:

Name, Number 
natto, 3 
eggs, 12 
shiitake, 1 
negi, 1 
garlic, 5 
umeboshi, 1 

樣本輸出目標:

number of integers in file "groceries.csv" = 6 
    index = 0, element = 3 
    index = 1, element = 12 
    index = 2, element = 1 
    index = 3, element = 1 
    index = 4, element = 5 
    index = 5, element = 1 

很抱歉的類似的問題。我非常強調了,更是我在做這一切錯了......我完全被卡住在這一點:(

+0

你應該閱讀[這](http://stackoverflow.com/a/21300653/2970947)再回答。特別是最後的'printf'。 –

+0

是否使用絕對強制的數組?你最好使用一個'List'實現(例如''ArrayList''):這樣你就沒有義務在開始時聲明它的大小,並且你不必管理你放入它的項目的索引。 –

+0

不幸的是我必須爲這個程序使用一個數組。 –

回答

0

這裏是爲了滿足您的新的需求的一種方式,

public static Integer[] readFileReturnIntegers(
    String filename) { 
    Integer[] temp = 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) { 
    // loop through file for integers and store in array 
    try { 
     while (inputFile.hasNext()) { 
     try { 
      temp[i] = inputFile.nextInt(); 
      i++; 
     } catch (InputMismatchException e) { 
      inputFile.next(); 
     } 
     } 
    } finally { 
     inputFile.close(); 
    } 
    Integer[] array = new Integer[i]; 
    System.arraycopy(temp, 0, array, 0, i); 
    return array; 
    } 
    return new Integer[] {}; 
} 

public static void printArrayAndIntegerCount(
    Integer[] array, String filename) { 
    System.out.printf(
     "number of integers in file \"%s\" = %d\n", 
     filename, array.length); 
    for (int i = 0; i < array.length; i++) { 
    System.out.printf(
     "\tindex = %d, element = %d\n", i, array[i]); 
    } 
} 

輸出

number of integers in file "/home/efrisch/groceries.csv" = 6 
    index = 0, element = 3 
    index = 1, element = 12 
    index = 2, element = 1 
    index = 3, element = 1 
    index = 4, element = 5 
    index = 5, element = 1 
+0

我設法瞭解它並正確地完成了我的程序!非常感謝Elliott!從一個不眠之夜裏直接救了我!我現在很開心! –

1

您可以用這種方式閱讀您的文件。

/* using Scanner */ 
public static Integer[] getIntsFromFileUsingScanner(String file) throws IOException { 
    List<Integer> l = new ArrayList<Integer>(); 
    InputStream in = new FileInputStream(file); 
    Scanner s = new Scanner(in); 
    while(s.hasNext()) { 
     try { 
      Integer i = s.nextInt(); 
      l.add(i); 
     } catch (InputMismatchException e) { 
      s.next(); 
     } 
    } 
    in.close(); 
    return l.toArray(new Integer[l.size()]); 
} 

/* using BufferedReader */ 
public static Integer[] getIntsFromFile(String file) throws IOException { 
    List<Integer> l = new ArrayList<Integer>(); 
    BufferedReader reader = new BufferedReader(new FileReader(file)); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     try { 
      l.add(Integer.parseInt(line.split(",")[1])); 
     } catch (NumberFormatException e) { 
     } 
    } 
    return l.toArray(new Integer[l.size()]); 
}  

和你的代碼:

public static void main(String[] commandlineArgument) { 
     Integer[] array = getIntsFromFileUsingScanner(commandlineArgument[0]); 
     ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]); 
    } 
+0

嘿marioosh,謝謝你的輸入。但我試圖循環使用Scanner構造函數,hasNextLine(),next()和nextInt()方法。最重要的是使用inputmismatchexception的try和catch。所以沒有列表和緩衝讀取器:( –

+0

更新了我的答案;) – marioosh

0

也許你可以通過簡短的代碼解決這個問題,我在下面發表。

public static List<Integer> readInteger(String path) throws IOException { 
    List<Integer> result = new ArrayList<Integer>(); 
    BufferedReader reader = new BufferedReader(new FileReader(path)); 
    String line = null; 
    Pattern pattern = Pattern.compile("\\d+"); 
    Matcher matcher = null; 
    line = reader.readLine(); 
    String input = null; 
    while(line != null) { 
     input = line.split(",")[1].trim(); 
     matcher = pattern.matcher(input); 
     if(matcher.matches()) { 
      result.add(Integer.valueOf(input)); 
     } 
     line = reader.readLine(); 
    } 
    reader.close(); 
    return result; 
} 
0

下面附上代碼嘗試捕捉:

try 
{ 
    if (inputFile.hasNextInt()) { 
     array[i] = inputFile.nextInt(); 
     i++; 
    } 
    else { 
     inputFile.next(); 
     } 
}catch(Exception e) 
{ 
    // handle the exception 
} 
相關問題