gpt4 book ai didi

从 .txt 文件扫描时出现 java.util.InputMismatchException 错误

转载 作者:行者123 更新时间:2023-12-01 04:15:53 25 4
gpt4 key购买 nike

我正在创建一个使用 2 个类的程序。在一个类中,我创建了然后由第二个类调用的方法。所有方法都包含在第一个类中,第二个类只是调用它们并执行代码。

1 级

 import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Student {


private Scanner scanner;
private String firstName;
private String lastName;
private int homeworkScore;
private int testScore;
private String letterGrade;
private int numberOfStudents;

public Student () {

String firstName = null;
String lastName = null;
int homeworkScore = 0;
int testScore = 0;
String letterGrade = null;
int numberOfStudents = 0;
}


public void openFile(){
try {
scanner = new Scanner(new File("grades.txt"));
} catch (FileNotFoundException e) {
System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
System.exit(0);
}
}


public void setNumberOfStudents() {
System.out.println("It kinda works");
numberOfStudents = scanner.nextInt();
}

public void setFastName() {
fastName = scanner.next();
}

public void setLastName() {
lastName = scanner.next();
}

public void setHomeworkScore() {

int subAssignment = 0;
int assignment = 0;

for(int i = 1; i <= 21; i++) {
subAssignment = scanner.nextInt();
assignment += subAssignment;
}

homeworkScore = assignment;
}

2级

  import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class CourseGrade {

public static void main(String[] args) {

Student myStudent = new Student();

myStudent.openFile();

myStudent.setNumberOfStudents();

myStudent.setFirstName();

myStudent.setLastName();

myStudent.setHomeworkScore();


}

}

这是我得到的错误:

 It kinda works
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Student.setHomeworkScore(Student.java:54)
at CourseGrade.main(CourseGrade.java:20)

...“It kinda Works”语句只是为了查看它是否正确调用了该方法,看起来确实如此。

据我了解,该错误告诉我它从 .txt 文件中读取了错误的类型,但我不知道为什么会这样。它甚至正确读取文件吗?任何类型的帮助都会很棒,因为我已经盯着并弄乱了这段代码几个小时了!

最佳答案

根据错误消息以及错误发生的位置,您很可能正在尝试读取整数,但您正在读取的实际数据不是数字。

您可以通过将 scanner.nextInt() 更改为 scanner.next() 并打印出您实际获得的值来验证这一点。或者,您可以添加以下形式的“错误处理”:

    for(int i = 1; i <= 21; i++) { 
if (scanner.hasNextInt()
subAssignment = scanner.nextInt();
else
throw new RuntimeException("Unexpected token, wanted a number, but got: " + scanner.next());
assignment += subAssignment;
}

关于从 .txt 文件扫描时出现 java.util.InputMismatchException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19460288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com