2016-11-08 2 views
0

(java.util.Scannerに)私はエラーが何であるかを把握することはできません1980年から2006年にハリケーンについての情報を含むファイルを読み込む必要はあり割り当てを持っています。私は次のようなコードセクションを持っています:java.util.InputMismatchException;ヌル

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 

public class Hurricanes2 
{ 
public static void main(String[] args)throws IOException 
{ 
    //declare and initialize variables 


    int arrayLength = 59; 
    int [] year = new int[arrayLength]; 
    String [] month = new String[arrayLength]; 



    File fileName = new File("hurcdata2.txt"); 
    Scanner inFile = new Scanner(fileName); 

    //INPUT - read data in from the file 
    int index = 0; 
    while (inFile.hasNext()) { 
     year[index] = inFile.nextInt(); 
     month[index] = inFile.next(); 
    } 
    inFile.close(); 

これはちょうど最初の部分です。しかし、whileステートメントのセクションでは、year[index] = inFile.nextInt()にエラーがあります。私はエラーが何を意味するか分からず、助けが必要です。前もって感謝します。

答えて

0

whileループの最後の行にインデックス++を追加してみてください。今のように、あなたはそれを増やすことはないので、配列内の最初の数字を塗りつぶして置き換えるだけです。

+0

が、私はこれとそれを試してみましたエラーを変更しませんでした。しかし、助けてくれてありがとう。 –

0

私は個人的にScanner()代わりFiles.readAllLines()使用することはありません。ハリケーンのデータを分割するためにある種の区切り文字があると、実装が簡単になるかもしれません。例えば

、のは、テキストファイルがこれですと言ってみましょう:

1996, August, 1998, September, 1997, October, 2001, April...

私はホールド真の作ったこれらの仮定場合は、次の操作を行うことができます。

Path path = Paths.get("hurcdata2.txt"); 
String hurricaineData = Files.readAllLines(path); 

int yearIndex = 0; 
int monthIndex = 0; 

// Splits the string on a delimiter defined as: zero or more whitespace, 
// a literal comma, zero or more whitespace 
for(String value : hurricaineData.split("\\s*,\\s*")) 
{ 
    String integerRegex = "^[1-9]\d*$"; 
    if(value.matches(integerRegex)) 
    { 
     year[yearIndex++] = value; 
    } 
    else 
    { 
     month[monthIndex++] = value; 
    } 
}