The code keeps print the text in try before printing error in the catch

Viewed 16

The requirement is to input until it is a digit. I created a try-catch within a while loop, the code was supposed to print "Please enter number" before forcing it to print "Enter number", however, the output was reversed. I found out the reason was from the return type, if I change the return type to void, the code will execute properly. Is there any way to keep the return type as float but still print in the right order? Below is the code that has return type as "float"

float inputDigit() {
    Scanner sc = new Scanner(System.in);
    float digit = 0;
    while (true) {
        try {
            System.out.print("Enter number: ");
            digit = Float.parseFloat(sc.nextLine());
            return digit;
        } catch (NumberFormatException e) {
            System.err.println("Please input number");
        }
    }
}
1 Answers

System.err and System.out are separate concepts. Your code will write to syserr, then loops and instantly writes to sysout. Effectively then, the 'Please input number' and 'Enter number' messages are sent at the exact same time (computers are just that fast).

One goes to the 'error stream', the other goes, simultaneously to the 'output stream', and as both are going to end up on your terminal they fight and randomly one wins. Sometimes they are in the right order, sometimes in the wrong. Changing the return type from float to void was irrelevant - just run it a few times.

By going with System.out for both, there is no racing. It's the simple way to solve this problem.

Related