Java 使用输入扫描仪时的输入不匹配异常

Java 使用输入扫描仪时的输入不匹配异常,java,java.util.scanner,inputmismatchexception,Java,Java.util.scanner,Inputmismatchexception,我正在写一个程序,可以读取各种类型的数据文件。我正在尝试将数据从文件传递到我创建的各种数组中 文件中的示例部分(换行符的间距为两倍。类别之间的空格为制表符,而名字/姓氏和国家之间的空格为空格) 然而,当我的代码编译时,我得到了InputMismatchException。我想知道它是否处理了这样一个事实,即在每一行的末尾,没有随后出现的制表符。有人能帮我度过这段时间吗 public static void main(String[] args) { Scanner console = new S

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

文件中的示例部分(换行符的间距为两倍。类别之间的空格为制表符,而名字/姓氏和国家之间的空格为空格)

然而,当我的代码编译时,我得到了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();
}

}
publicstaticvoidmain(字符串[]args){
扫描仪控制台=新扫描仪(System.in);
简介();
扫描仪输入1=空;
扫描仪输入2=空;
int lineCount=0;
试一试{
input1=新扫描仪(新文件(“olympicstest.txt”);
} 
catch(filenotfounde异常){
System.out.println(“无效选项”);
系统出口(1);
}
while(input1.hasNextLine()){
lineCount++;
input1.nextLine();
}
lineCount=lineCount-1;
String[]country=新字符串[lineCount];
int[]totalcoulders=新的int[lineCount];
字符串[]名称=新字符串[行数];
int[]年龄=新int[lineCount];
整数[]年=新整数[行数];
字符串[]运动=新字符串[行数];
试一试{
input2=新扫描仪(新文件(“olympicstest.txt”);
input2.useDelimiter(“\t”);
} 
catch(filenotfounde异常){
System.out.println(“无效选项”);//不确定是否需要此行
System.exit(1);//不确定是否需要此行
}        
字符串lineDiscard=input2.nextLine();
对于(int i=0;i
是的,关于问题的原因,您是对的。一个解决方案是在
usedimiter
调用中使用一个正则表达式,它同时接受制表符和换行符。所以你会这样做:

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

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

你说这是你的输出,不是指输入吗?你是对的。它应该读取输入。现在修好。
input2.useDelimiter("[\t\n]");