[Solved] System.exit(0) Is not working [duplicate]


if (t <0 && t>11) System.exit(0);

A number can’t be smaller than 0 and bigger than 11 at the same point in time. Or to be precise: the numerical types that Java support don’t allow for that.

In that sense, you probably meant:

if (numberFromUser < 0 || numberFromUser > 11) {
 System.out.println("number " + numberFromUser + " is invalid, exiting");
 System.exit(1);
}

And please note changes I made:

  • t is an absolutely pointless name – use names that mean something
  • always always always use { braces } – even for such simple one line statemeents
  • just exiting is a bad idea: you want to give the user feedback what went wrong. Or do you like it when your computer just stops something doing without telling you why?
  • and then: you have an empty catch block – another super bad idea. There is no point in suppressing error messages. Aren’t you interested in understanding when your program runs into errors?!
  • The value passed to System.exit() is the “return code” of your application. And by convention, returning zero means: all fine, passed. Thus you should return something other than zero in error cases.

And finally: using System.exit() all over the place is by itself bad practice. You really do not want that your application has more than one exit() point. In other words: you should design your whole application to use exceptions for example. When there are real “hard” problems – give a good message to the user, and throw an exception (which maybe your top layer catches and turns into a meaningful, defined non-zero return code).

6

solved System.exit(0) Is not working [duplicate]