java.util.InputMismatchException; null(在java.util.Scanner中)
问题描述:
我有一个任务,我必须在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()
有错误。我不知道错误意味着什么,我需要帮助。提前致谢。
答
尝试添加index ++作为while循环的最后一行。就像现在一样,你永远不会增加它,所以你只能填充和替换数组中的第一个数字。
答
我个人不会使用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;
}
}
我想这和它没有改变错误。感谢您尽力帮助。 –