2012-11-25 46 views
0

可能重複:
Scanner issue when using nextLine after nextInt試圖讀取Java中的文件......有問題

我很新的編程,我得到了一個錯誤,沒有任何意義我(我會在這裏搜索答案,但我很難確定問題)。我正在嘗試讀取有颶風數據的文件。 是文件的前幾行如下:

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

我不知道我做錯了什麼。

回答

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++;  
} 
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()將其讀取。

+0

我仍然正在錯誤Java.util.InputMismatchException null(在java.util.Scanner中)......有沒有這個可能發生的任何其他原因? – anoop