2016-11-08 44 views
0

我有一個任務,我必須在1980年到2006年的文件中閱讀有關颶風的信息。我無法弄清楚錯誤是什麼。我有一段代碼是這樣的:java.util.InputMismatchException; null(在java.util.Scanner中)

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

嘗試添加index ++作爲while循環的最後一行。就像現在一樣,你永遠不會增加它,所以你只能填充和替換數組中的第一個數字。

+0

我想這和它沒有改變錯誤。感謝您盡力幫助。 –

0

我個人不會使用Scanner()而是使用Files.readAllLines()。如果存在某種劃分角色來分割Hurricaine數據,實現起來可能更容易。

例如,假設您的文本文件是這樣的:

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; 
    } 
}