尝试读取具有各种但已知的输入类型的文件并获取InputMismatchException

时间:2019-03-31 01:26:48

标签: java inputmismatchexception

我正在尝试读取一个看起来像这样的文件

C 8230123345450 Simons Jenny R 0 12

C 3873472785863卡特曼·埃里克N 750 18

C 4834324308675麦考密克·肯尼R 0 20

O 1384349045225 Broflovski Kyle-6 //可能的问题开始

O 5627238253456沼泽斯坦T 3

要澄清: C =校园学生 O =在线学生

代码应确定学生是在校园还是在线,然后使用适当的方法并相应地阅读代码。我认为是credits变量的readOnlineStudent方法崩溃了。

引发InputMismatchException。

我不确定要尝试什么,因为一切都对我来说似乎很对(显然我缺少了某些东西)。

这是相关代码:

private ArrayList<Student>readFile() throws FileNotFoundException {
    ArrayList<Student> studentList;
    studentList = new ArrayList<>();
    Scanner in = new Scanner(new 
    File("C:\\Users\\KYLE\\Documents\\burger-cse205- 
    p02\\test\\input\\p02-students.txt"));

    while(in.hasNext() == true){
        String studentType = in.next();
        if(studentType == "C"){
            studentList.add(readOnCampusStudent(in));
        }
        else{
            studentList.add(readOnlineStudent(in));
        }
    }
    in.close();
    return studentList;
}

private OnCampusStudent readOnCampusStudent(Scanner pIn){
    String id = pIn.next();
    String lname = pIn.next();
    String fname = pIn.next();
    OnCampusStudent student = new OnCampusStudent(id, fname, lname);
    String res = pIn.next();
    double fee = pIn.nextDouble();
    int credits = pIn.nextInt();
    if(res.equals("R")){
        student.setResidency(OnCampusStudent.RESIDENT);
    }
    else{
        student.setResidency(OnCampusStudent.NON_RESIDENT);
    }
    student.setProgramFee(fee);
    student.setCredits(credits);
    return student;
}

private OnlineStudent readOnlineStudent(Scanner pIn){
    String id = pIn.next();
    String lname = pIn.next();
    String fname = pIn.next();
    OnlineStudent student = new OnlineStudent(id, fname, lname);
    String fee = pIn.next();
    int credits = pIn.nextInt(); //this is the line that throws the error
    if(fee.equals("T")){
        student.setTechFee(true);
    }
    else{
        student.setTechFee(false);
    }
    student.setCredits(credits);
    return student;
}

该如何解决?

谢谢

2 个答案:

答案 0 :(得分:1)

您有条件

if(studentType == "C") { 

应替换为

if(studentType.equals(C")) {

==比较引用,而equals比较实际值

答案 1 :(得分:0)

您的积分值对于int类型而言太大。使用长数据类型,并使用nextLong()代替nextInt()
简而言之:

int credits = pIn.nextInt();
// should be...
long credits = pIn.nextLong();