Java Scanner is appearing before print()

Viewed 667

I am trying to print a string before asking for the input while using Scanner, but it keeps making the input appear before the string. I can't find any reason why it's doing this. I have attached the full code below.

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");
        }
    }
    
}
1 Answers

System.out.print may not flush to the screen immediately, but you could flush it explicitly:

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