我正在尝试使用扫描仪写入和读取 txt。但我一直收到这个错误“找不到行”
这是代码
public class LoadAndStoreDataToFile {
final static String FULLTIMETYPE = "FULLTIME";
final static String PARTTIMETYPE = "PARTTIME";
final static String FILENAME = "students.obj";
public static Student createStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter student ID: ");
String sID = sc.nextLine();
System.out.print("Enter student full name: ");
String sFullName = sc.nextLine();
System.out.print("Enter student major (IT, SE, IS, etc.): ");
String sMajor = sc.nextLine();
System.out.print("Enter student type (FULLTIME or PARTTIME): ");
String sType = sc.nextLine();
System.out.print("Enter student GPA: ");
double sGPA = sc.nextDouble();
Student student;
if (sType.toUpperCase().equals(FULLTIMETYPE)) {
student = new FullTimeStudent(sID, sFullName, sMajor, sGPA);
} else if (sType.toUpperCase().equals(PARTTIMETYPE)) {
System.out.print("Enter student min hour: ");
int minHour = sc.nextInt();
System.out.print("Enter max hour: ");
int maxHour = sc.nextInt();
student = new PartTimeStudent(sID, sFullName, sMajor, sGPA, minHour, maxHour);
} else {
System.out.println("Student type must be Fulltime or Parttime");
student = null;
}
sc.close();
return student;
}
// Allow the user to create several student objects
public static void getDataFromUser(List<Student> students) {
Scanner sc = new Scanner(System.in);
boolean wantToExit;
System.out.print("Create a new student (Enter) or Exit (X, then Enter)? ");
wantToExit = sc.nextLine().equals("X");
while(true) {
if (wantToExit == false) {
Student student = createStudent();
if (student != null) {
students.add(student);
}
} else {
break;
}
}
sc.close();
System.out.println("getDataFromUser is done!");
}
}
我尝试将 sc.close 放在别处,但错误仍然存在。我知道这是 hasnext() 或 nextline() 的问题,但找不到问题发生的位置。
编辑:错误发生在 createStudent()