2016-11-12 9 views
0

私はtxtファイルから読み込んだtxt情報をcarオブジェクトに変換してarraylistに追加するプログラムを持っています。txtファイルから読み込むときのエラー処理

try { 
    String filePath = "car.txt"; 
    File f = new File(filePath); 
    Scanner sc = new Scanner(f); 


    List<Car> car = new ArrayList<Car>(); 

    while(sc.hasNextLine()){ 
     String newLine = sc.nextLine(); 

     String[] details = newLine.split(" "); 
     String brand = details[0]; 
     String model = details[1]; 
     double cost = Double.parseDouble(details[2]); 
     Car c = new Car(brand, model, cost); 
     Car.add(c); 
    } 

ただし、txtファイルの行に3つのコンポーネントが含まれていないと、クラッシュします。メッセージを印刷して終了しないと、行に3つのコンポーネントがすべて含まれているかどうかを確認するにはどうすればよいですか?

スタックトレース - 以下に示すように

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 
at Main.loadPerson(Main.java:31) 
at Main.main(Main.java:12) 
+0

の要素にアクセスする前に、スタックトレース – ItamarG3

+0

チェック '' details'のlength'を示してください、あなたは 'ArrayIndexOutOfBoundsException'を得る可能性があります – Saravana

答えて

0

あなたが細部のlengthをチェックする必要があるが、3番出口の場合ではありません。

 String[] details = newLine.split(" "); 
    if(details.length != 3) { 
     System.out.println("Incorrect data entered !! Please try again !!! "); 
     return; 
     } else { 
     String brand = details[0]; 
     String model = details[1]; 
     double cost = Double.parseDouble(details[2]); 
     Car c = new Car(brand, model, cost); 
     Car.add(c); 
    } 
0

あなたは、スプリットからの戻り配列の長さを確認することができますby:

int count = details.length; 

そして、何をすべきかを決定します。

0

チェック長さの要素にアクセスする前に、

は、スペースをトリミング避けるために、パターン\\s+を試みるファイルが含まれていない場合は、車のリスト

while (sc.hasNextLine()) { 
     String newLine = sc.nextLine(); 
     String[] details = newLine.split("\\s+"); 
     if (details.length == 3) { 
      String brand = details[0]; 
      String model = details[1]; 
      double cost = Double.parseDouble(details[2]); 
      Car c = new Car(brand, model, cost); 
      car.add(c); 
     } else { 
      System.out.println("Invalid input"); 
     } 
    } 
0

に車を追加し、あなたのコード内の誤植があります3つのコンポーネントの場合、detailsは空になります。これを代わりに使用してください。

if(details.length() != 3){ 
    System.out.println("Invalid .txt file!"); 
    break; 
} 
関連する問題