我正在编写一个读取各种类型数据文件的程序。我正在尝试将文件中的数据传递给我创建的各种数组。
文件中的示例部分(双倍行距。类别之间的空格是制表符,但名字/姓氏和国家/地区之间的空格是空格)
Name Age Country Year Closing Date Sport Gold Silver Bronze Total
Joe Max 24 Algeria 2012 8/12/2012 Athletics 1 0 0 1
Tom Lan 27 United States 2008 8/24/2008 Rowing 0 1 0 1
然而,当我的代码编译时,我得到了 InputMismatchException。我想知道它是否处理在每一行的末尾没有随后出现的选项卡的事实。谁能帮我解决这个问题?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();
Scanner input1 = null;
Scanner input2 = null;
int lineCount = 0;
try {
input1 = new Scanner(new File("olympicstest.txt"));
}
catch (FileNotFoundException e) {
System.out.println("Invalid Option");
System.exit(1);
}
while (input1.hasNextLine()) {
lineCount++;
input1.nextLine();
}
lineCount = lineCount - 1;
String[] country = new String[lineCount];
int[] totalMedals = new int[lineCount];
String[] name = new String[lineCount];
int[] age = new int[lineCount];
int[] year = new int[lineCount];
String[] sport = new String[lineCount];
try {
input2 = new Scanner(new File("olympicstest.txt"));
input2.useDelimiter("\t");
}
catch (FileNotFoundException e) {
System.out.println("Invalid Option"); // not sure if this line is needed
System.exit(1); // not sure if this line is needed
}
String lineDiscard = input2.nextLine();
for (int i = 0; i < lineCount; i++) {
name[i] = input2.next();
age[i] = input2.nextInt();
country[i] = input2.next();
year[i] = input2.nextInt();
input2.next(); // closing ceremony date
sport[i] = input2.next();
input2.nextInt(); // gold medals
input2.nextInt(); // silver medals
input2.nextInt(); // bronze medals
totalMedals[i] = input2.nextInt();
}
}