0

重複の可能性:
nextInt の後に nextLine を使用する場合のスキャナーの問題

私はプログラミングに非常に慣れていないので、意味をなさないエラーが発生しました(ここで答えを検索したはずですが、問題をほとんど特定できません)。ハリケーン データを含むファイルを読み込もうとしています。ファイルの最初の数行は次のとおりです。

1980 Aug    945 100 Allen
1983 Aug    962 100 Alicia
1984 Sep    949 100 Diana
1985 Jul    1002    65  Bob
1985 Aug    987 80  Danny
1985 Sep    959 100 Elena
1985 Sep    942 90  Gloria
1985 Oct    971 75  Juan

ファイルを試して読み取るための私のコードは次のとおりです。

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Hurricanes2


{
    public static void main(String[] args)
    {  



    double categoryAverage = 0.0;
    int categorySum = 0;
    int counter = 0;

    File fileName = new File("hurcdata2.txt");
    Scanner inFile = new Scanner("hurcdata2.txt");
    int[] year = new int[59];
    String[] month = new String[59];
    int[] pressure = new int[59];
    int[] windSpeed = new int[59];
    String[] hurcName = new String[59];

    while(inFile.hasNext())
    {
    year[counter] = inFile.nextInt();
    month[counter] = inFile.next();
    pressure[counter] = inFile.nextInt();
    windSpeed[counter] = inFile.nextInt();  
    hurcName[counter] = inFile.next();
    counter++;    

    }    

エラーが発生し続けます。Java.util.InputMismatchException が発生し、次の行が強調表示されます。

year[counter] = inFile.nextInt(); 

私は何が間違っていたのか分かりません。

4

2 に答える 2

0

この問題は、ファイルのすべての行の終わりに改行文字があるために発生します。最初の行のエントリを読み取った後、改行文字でスタックし、int(year [counter] = inFile.nextInt())ではないため、不一致の例外が発生します。

この問題を修正するには、以下にステートメントを追加して改行文字を読み取り、このステートメントの後に無視しますhurcName[counter] = inFile.next();

      inFile.nextLine();

以下のように完全に更新されたwhileループ:

while(inFile.hasNext())
{
   year[counter] = inFile.nextInt();
   month[counter] = inFile.next();
   pressure[counter] = inFile.nextInt();
   windSpeed[counter] = inFile.nextInt();  
   hurcName[counter] = inFile.next();

   //read the new line character at the end and ignore it
   inFile.nextLine();
   counter++;    
}   
于 2012-11-25T21:45:43.510 に答える
0

whileループを次のように置き換えます。

while(inFile.hasNextLine())
{
    year[counter] = inFile.nextInt();
    month[counter] = inFile.next();
    pressure[counter] = inFile.nextInt();
    windSpeed[counter] = inFile.nextInt();  
    hurcName[counter] = inFile.next();
    inFile().nextLine(); // to consume the new line character '\n'
    counter++;    
}

Java.util.InputMismatchException\nwhileループの最後でを読み取っていないためにスローされ、代わりに最初にinFile.nextInt()読み取られます。

于 2012-11-25T21:46:41.580 に答える