3

This code is part of a program.

System.out.print("Enter your deposit amount: ");
double deposit = scanner.nextDouble();
bankObj.deposit(deposit); //this method will print a syserr if the number entered is negative
if (deposit > 0) {
    System.out.println("Thank you for depositing the amount of "+deposit+" to account number "+bankObj.accountNum+".");
}
    System.out.println("Program exiting.");

Output:

Enter your deposit amount: -2
//sometimes it will print.
Program exiting.
Account.deposit(...): cannot deposit negative amount. //This is from the deposit method
//or
Account.deposit(...): cannot deposit negative amount. //This is from the deposit method
Program exiting.

Why is this happening? I tried putting it outside loops and statements (those might be the problem) but the behavior didn't change. I'm using Eclipse.

wormwood
  • 441
  • 4
  • 9
  • 17

1 Answers1

6

Those are two different output streams, the order in which they are invoked is not the only thing that matters. They might flush their contents towards the console at a different time.

Edit: after a bit more digging this answer indicates that it might be an (unresolved) eclipse bug as well. It's been open for 10 years, don't get your hopes up on a fix anytime soon.

Community
  • 1
  • 1
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • So is there a way to fix it, like at least making the syserr appear before the sysout? – wormwood Nov 18 '13 at 16:25
  • Both `System.out` and `System.err` are a `Printstream` so you can try manually flushing them (`System.out.flush()`). http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html – Jeroen Vannevel Nov 18 '13 at 16:27