Java 扫描仪出现在 print() 之前

Java Scanner is appearing before print()

我在使用 Scanner 时尝试在请求输入之前打印一个字符串,但它一直使输入出现在字符串之前。我找不到它这样做的任何理由。我在下面附上了完整的代码。

import java.util.Scanner;


public class FizzBuzz {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Number: ");
        long number = scanner.nextLong();
        
        if (number % 5 ==0) {
            System.out.print("Fizz");
        }
        else if (number % 3 ==0) {
            System.out.println("Buzz");
        }
        else if ((number % 5 ==0) && (number % 3 ==0)) {
            System.out.println("FizzBuzz");
        }
        else {
            System.out.println(number + " Is neither Fizzable or Buzzable");
        }
    }
    
}

System.out.print 可能不会立即刷新到屏幕,但您可以显式刷新它:

System.out.print("Number: ");
System.out.flush(); // here!
long number = scanner.nextLong();