试图在java中读取文件...有问题

时间:2012-11-25 21:42:21

标签: java file-io

  

可能重复:
  Scanner issue when using nextLine after nextInt

我是编程的新手,我得到了一个没有意义的错误(我会在这里搜索答案,但我很难确定问题)。我正在尝试读取具有飓风数据的文件。 文件的前几行如下:

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(); 

我不知道我做错了什么。

2 个答案:

答案 0 :(得分:0)

问题是由于文件中每一行末尾都有新的换行符。在读完第一行条目后,它会卡在新行字符上,并给出不匹配异常,因为它不是int(年[计数器] = inFile.nextInt())。

要解决此问题,请在下面添加语句以读取新行char并在此语句后忽略它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++;    
}   

答案 1 :(得分: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被抛出是因为您没有在while循环结束时阅读\n,而是第一个inFile.nextInt()读取它。