This isn't a major issue, but I don't understand why this happens, so I figured I'd post it here. This is my code:
do{
printMenu();//method to print menu
try{
user=input.nextInt();
}
catch(InputMismatchException imme)
{
System.err.println("Make sure to enter a number.");
input.next();
continue;
}
switchMenu(user);//method with switch method for user input
}while(1<2);
The code runs fine except for one thing. The error message Make sure to enter a number. sometimes displays after the menu, sometimes before, sometimes in the middle of the menu. This is the output of the program:
1. Book a ticket
2. Cancel a ticket
3. Check how many seats left
4. Print seat map
5. Check price
6. Print ticket
7. Exit
a
1. Book a ticket
2. Cancel a ticket
3. Check how many seats left
4. Print seat map
5. Check price
6. Print ticket
7. Exit
Make sure to enter a number.//Error message after menu
asd//wrong input
Make sure to enter a number.//now error message displays before menu
1. Book a ticket
2. Cancel a ticket
3. Check how many seats left
4. Print seat map
5. Check price
6. Print ticket
7. Exit
asd
1. Book a ticket
2. Cancel a ticket
3. Check how many seats left
Make sure to enter a number.//in the middle now???
4. Print seat map
5. Check price
6. Print ticket
7. Exit
I am using Eclipse if it matters. I know it's not a big problem, but I'm curious why this happens.
This is due to the fact that System.out
and System.err
are two different streams which might buffer write operations and get flushed (i.e. printed out) at different times.
Things probably get mixed up between System.out
and System.err
, because I'd assume System.out
to be implemented using a buffered output stream for performance reasons and System.err
to be implemented using a non-buffered stream to get error messages printed more quickly.
You will probably observe a behaviour closer to what you expect when you explicitly call flush()
on the streams, although I'm not sure if there won't be race conditions left, as both will end up in the same Eclipse console.
That being said, I'd also assume that the Eclipse console has means of mixing up strings (i.e. even if your code guarantees an order, the console might give System.err
a higher priority), so the only reliable way of getting a guaranteed order would IMHO be using the same output stream for both messages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With