Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch Statement

 
Marving Guildon
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, it works.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

  •  
    Ben Poole
    Ranch Hand
    Posts: 33
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic