I am creating a program where 2 classes are used. In one class, i create methods that are then called by the second class. All methods are contained in the first class and the 2nd class simply calls them and executes the code.
Class 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;
}
Class 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();
}
}
This is the error I get:
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)
...the "It kinda works" statement is just to see if it was calling the method correctly, which it looks like it is.
To my understanding, the error is telling me that it is reading the wrong type from the .txt file, but idk why that would be. Is it even reading the file correctly? Any type of help would be great, as I have been staring and messing with this code for hours!
intas expected.