2016-04-28 13 views
-1

読むファイル:私の読み込みファイルの方法を修正するにはどうしたらいいですか?

このメソッドは、ファイルの名前である単一のパラメータを持っています。
このメソッドの目的は、ファイルの内容を配列に読み込むことです。
try/catchブロックとスキャナオブジェクトを使用する必要があります。
ファイルの最初の行には、行数を指定する整数があります。
この値を変数numberLinesに読み込みます。
もう一度nextLineを呼び出すと、残りの行が破棄されます。
fileContents配列にnumberLineThe要素を割り当てるように割り当てます。
指定された行数をfileContentsに読み込むforループを作成します。
catch例外コードは何もしないか、エラーを報告する必要があります。

これは私の現在のコードです。私は間違って何をしていますか?

public void readFile(String filename) { 
     // TODO Auto-generated method stub 
     try { 

      Scanner read = new Scanner(new File(filename)); 
      int[] fileContents = {numberLines}; 
      numberLines = read.nextInt(); 
      read.nextLine(); 

      for(int i = 0; i < numberLines; i ++){ 

       fileContents[i] = read.nextInt(); 

       read.close(); 
      } 

     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

答えて

0
public void readFile(String filename) { 
     // TODO Auto-generated method stub 
     try { 

      Scanner read = new Scanner(new File(filename)); 
      //int[] fileContents = {numberLines}; //fileContents has one element 
      numberLines = read.nextInt(); 
      //you can read numberLines first and then create fileContents array as you wish 
      int[] fileContents = new int[numberLines]; 
      //if each line only contains a number, you can read line to String and convert it to int 
      //read.nextLine(); 

      for(int i = 0; i < numberLines; i ++){ 
       String nextLine = read.nextLine(); 
       //fileContents[i] = read.nextInt(); 
       fileContents[i] = Integer.parseInt(nextLine); 
       //read.close(); 
      } 
      //close read after all lines were read 
      read.close(); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

いくつかの例外が多分スロー:

NoSuchElementException - 何行が

IllegalStateExceptionを発見されなかった場合 - このスキャナが

+0

閉じている場合、私が試したし、まだメソッドを呼び出すことはできませんと言います.... –

+0

この警告(またはエラー)は、どの行に表示されますか? –

+0

それは言わない。私が課題を提出すると、その部分に「メソッドを呼び出すことはできません:readFile」と表示されます –

関連する問題