我是Java的新手,并跟随Murach的Java书中的示例。我目前正在学习如何处理记录。我遇到了一个似乎无法解决的问题。逻辑编译没有任何问题,但是,当我尝试运行该程序时,在“ ReadRecords”类的第23行收到“ INputMismatchException”错误。我已经用谷歌搜索了这个问题,并在SOF上搜索了这个问题,我确实找到了几个解决方案,但是它们并没有帮助。如果有人可以帮助我解决此问题,我将不胜感激。我有这些课:
唱片班
ReadRecords类
记录代码类:
class Records{
public int id; //ID
public String name; //NAME
public String gender; //GENDER
}//CLASS
ReadRecords类的代码:
import java.util.Scanner;
import java.io.*;
public class ReadRecords {
//METHOD: MAIN
public static void main(String[] args){
Scanner input;
final int MAX_LEN = 25;
int counter = 0;
String filePath = "files/records.txt";
Records[] rec = new Records[ MAX_LEN ];
File file;
try {
file = new File( filePath );
input = new Scanner( file );
do{
rec[counter].id = input.nextInt(); //INT
rec[counter].name = input.next(); //STRING
rec[counter].gender = input.next(); //STRING
++counter;
}
while(rec[counter -1].id != 0);
}
catch ( IOException ex ){
System.out.println( "File access error" );
counter = 0;
}//
System.out.println(rec[0].name);
}//
}//
文本文件“ records.txt”
1, Adam, male
2, Bella, female
3, Charlie, male
4, David, male
5, Elizabeth, female
6, Frank, male
7, Ginger, female
8, Harry, male
9, Irene, female
10, Jill, female
谢谢。
最佳答案
您正在搜索的输入是int
,但是您首先输入了string
,所以您将获得inputMismatchException,因为扫描仪的默认斜线是空格,
在文本文件中,您以“,”作为定界符。
input = new Scanner( file ).useDelimiter(", ");
其次,
rec[counter].id
引发NullPointerException
,因为您最初在数组中将具有空值。因此,如下所示进行更改do{
Records record=new Records();
record.id = input.nextInt(); //INT
record.name = input.next(); //STRING
record.gender = input.next(); //STRING
rec[counter]=record;
++counter;
}
while(input.nextLine() != null);