简体   繁体   中英

Java Scanner is appearing before print()

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM