为什么扫描仪在输出之前读取?

Why is the scanner reading before the output?

我正在尝试在 java 中做一些事情,我需要在扫描仪从控制台读取新行之前打印输出,但由于某种原因输出仅在所有扫描调用之后出现,我会想知道这是为什么?

我之前曾尝试使用 Thread.sleep() 来解决问题,但没有成功。

这是函数所在的class:

public class librarySystem {

    private ArrayList<Student> students;
    private ArrayList<Book> books;
    private ArrayList<RentActivity> rents;

    public void addStudent() {
        System.out.print("Enter studnet ID: ");
        String studentID = LibProject.LibProjectMain.scanner.nextLine();
        if(!ParameterUtils.validId(studentID)) {
            System.err.println("Invalid student ID.");
            return;
        }
        if(ListUtils.containsStudentByID(students, studentID)) {
            System.err.println("Student ID already exists in the system.");
            return;
        }
        System.out.print("Enter first name: ");
        String firstName = LibProject.LibProjectMain.scanner.nextLine();
        if(!ParameterUtils.validPersonName(firstName)) {
            System.err.println("Invalid first name.");
            return;
        }
        System.out.print("Enter last name: ");
        String lastName = LibProject.LibProjectMain.scanner.nextLine();
        if(!ParameterUtils.validPersonName(lastName)) {
            System.err.println("Invalid last name.");
            return;
        }
        System.out.print("Enter student email: ");
        String email = LibProject.LibProjectMain.scanner.nextLine();
        if(!ParameterUtils.validEmail(email)) {
            System.err.println("Invalid email.");
            return;
        }
        Student student = new Student(studentID,firstName,lastName,email);
        this.students.add(student);
        FileUtils.writeStudent(student);
        System.out.println(firstName + " " + lastName + " added successfully to the system.");
    }
}

这是主要的 class,主要功能和扫描仪都位于此处:

public class LibProjectMain {
    
    public static final Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) throws InterruptedException {
        LibrarySystem LS = new LibrarySystem();
        boolean keepGoing = true;
        LS.addStudent();
    }
}

这是预期的输出:

Enter Student ID: 123456789
Enter first name: Bob
Enter last name: Freeman
Enter student email: bobfreeman@mail.com
Bob Freeman added successfully to the system.

真实输出:

123456789
Bob
Freeman
bobfreeman@mail.com
Enter studnet ID: Enter first name: Enter last name: Enter student email: Bob Freeman added successfully to the system.

System.out PrintStream 在 println 方法或写入 \n 时自动刷新。如果想使用System.out.print而不写\n,可以考虑使用System.out.flush方法:

System.out.print("Enter student ID: ");
System.out.flush();
String studentID = LibProject.LibProjectMain.scanner.nextLine();

有关此主题的更多信息,请参阅 PrintStream java docs