I am trying to read a file that looks exactly like this
C 8230123345450 Simons Jenny R 0 12
C 3873472785863 Cartman Eric N 750 18
C 4834324308675 McCormick Kenny R 0 20
O 1384349045225 Broflovski Kyle - 6 //possible problem start
O 5627238253456 Marsh Stan T 3
To clarify: C = OnCampusStudents O = OnlineStudents
The code should determine whether the student is on campus or online then use the appropriate method and the read the code accordingly. It is crashing in my readOnlineStudent method on what i believe is the credits variable.
Throws an InputMismatchException.
I'm not sure what to try because everything looks right to me (obviously I'm missing something).
Here is the relative code:
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;
}
What can be done to fix this?
Thanks
You have the condition
if(studentType == "C") {
which should be replaced with
if(studentType.equals(C")) {
==
compares references while equals compares actual values