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被抛出是因为你没有\n在 while 循环的末尾读取,而是第一个inFile.nextInt()读取它。

于 2012-11-25T21:46:41.580 回答