0

我正在编写一个读取各种类型数据文件的程序。我正在尝试将文件中的数据传递给我创建的各种数组。

文件中的示例部分(双倍行距。类别之间的空格是制表符,但名字/姓氏和国家/地区之间的空格是空格)

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

}
4

2 回答 2

1

是的,您对导致问题的原因是正确的。一种解决方案是在useDelimiter接受制表符和换行符的调用中使用正则表达式。所以你会这样做:

input2.useDelimiter("[\t\n]");

正则表达式的解释

于 2014-04-01T18:54:20.613 回答
1

是的,当您设置特定的分隔符时,不幸的是,它成为唯一用于分隔与您的.next()语句不匹配的值的分隔符,因此您可以将制表符 ( \t) 添加到每行的末尾,或者您可以同时设置\t\n到分隔符用正则表达式"[\t\n]"。我也更喜欢使用 CSV 格式,并用逗号分隔所有值,因为从视觉角度来看,制表符和空白字符通常不是很容易区分,所以我发现以后使用/格式化更容易

于 2014-04-01T19:01:45.347 回答