Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Switch Statement" Watch "Switch Statement" New topic

Switch Statement

Marving Guildon

Joined: Sep 17, 2003
Posts: 9
I have the following switch statement and I need to end the program if the user select number 2.

When the user select the number 2, the program still runing, but it needs to terminate.
li qing

Joined: Sep 27, 2003
Posts: 11
sorry... i'm not very good in java too... but maybe u can use System.exit(0); instead of break... and the case 2 should be default... as it is the last case...

Marving Guildon

Joined: Sep 17, 2003
Posts: 9
Thanks, it works.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Yes, System.exit(0) would end the program. But...
I wouldn't make 2 the default case. If you want the user to exit when explicitly selecting '2', then making all but '1' the default case would mean the program would exit if the user selected '3', or '4', or any value other than '1', which seems to go against what you wanted to do.
Anywho, that's my last 2 cents for today.

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
I think that System.exit() should rarely be used to end your program. A better way is to ensure that all your threads have finished (in a single-threaded program, this just means allowing main() to return).
There are a number of reasons for this: -
  • System.exit() causes an immediate exit. It does not take account of the state of other threads; they will all be forced to exit immediately.
  • A method with System.exit() is more difficult to re-use in another application.
  • The compiler does not realise that flow cannot go beyond a System.exit() call, and hence its ability to check whether you have unreachable code, missing "return", or suchlike, is compromised.

  • Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
    Ben Poole
    Ranch Hand

    Joined: Jul 17, 2003
    Posts: 33
    In addition, as a point of enlightenment, all "break" does is literally break out of the switch block... it has nothing to do with actually terminating your program. You can also use it in loops and so forth.
    I agree. Here's the link:
    subject: Switch Statement
    It's not a secret anymore!