stumped
stumped

Reputation: 3293

Ordering of error output

import java.util.Scanner;
import java.util.InputMismatchException;

public class Main
{
    public static int quotient(int a, int b) throws ArithmeticException
    {
        return a / b;
    }

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        boolean continueLoop = true;

        do
        {
            try
            {
                System.out.print("Enter integer numerator: ");
                int numerator = scan.nextInt();

                System.out.print("Enter integer denomiantor: ");
                int denominator = scan.nextInt();

                int result = quotient(numerator, denominator);
                System.out.println("Result: " + numerator + " / " + denominator
                        + " = " + result);
                continueLoop = false;
            } 

            catch (InputMismatchException inputMismatchException)
            {
                System.err.println("\nException: " + inputMismatchException);
                scan.nextLine();
                System.out.println("\nSolution: Must enter an integer");
            }

            catch (ArithmeticException arithmeticException)
            {
                System.err.println("\nException" + arithmeticException);
                System.out.println("Solution: Zero is an invalid denominator");
            }
        } while (continueLoop);
    }
}

Output:

Enter integer numerator: 5
Enter integer denomiantor: 0
Solution: Zero is an invalid denominator
Enter integer numerator: 
Exceptionjava.lang.ArithmeticException: / by zero

I'm confused on why did the System.err.println message was displayed at the end? And also why does an infinite loop occurs if I leave out scan.nextLine();?

Upvotes: 0

Views: 49

Answers (1)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

One at a time:

I'm confused on why did the System.err.println message was displayed at the end?

The output stream goes directly to your console. The error stream is buffered during execution, and is flushed when the program terminates. Hence it's appearing at the end.

And also why does an infinite loop occurs if I leave out scan.nextLine();?

It's still 'scanning' the previous line if you don't, always finding invalid integers, always throwing the exception, never getting to the point where continueLoop becomes false.

Upvotes: 2

Related Questions