java - Three exceptions for int -
i trying create code int supposed entered , have exceptions if int not between 9 , 99, exception if double entered instead of int , third exception if string entered. how do this? have below have far not sure how correct it. thanks
public static void main(string[] args) { scanner input = new scanner(system.in); boolean correct = true; { try { system.out.println("enter integer between 9 , 99"); int number = input.nextint(); if (number >= 9 && number <= 99) { system.out.println("thank you, initialization completed"); correct = false; } else if (number < 9 || number > 99) { throw new exception("integer not within range"); } if (input.hasnextdouble()) { throw new exception("integer not entered"); } else { correct = false; } if (input.hasnext("")) { throw new numberformatexception("integer not entered"); } else { correct = false; } } // check range catch (exception e1) { system.out.println("number not within 9 , 99"); system.out.println(); input.nextline(); } catch (exception e2) { system.out.println("an integer not entered"); system.out.println(); input.nextline(); } catch (numberformatexception e3) { system.out.println("an integer not entered"); system.out.println(); input.nextline(); } } while (correct); }
method .getmessage() returns string given in constructor:
throw new exception("here");
when catch exception, catch numberformatexception, inputmismatchexception, etc. must catch broader ones last.
catch (numberformatexception e3) { // precisier goes first system.out.println("an integer not entered"); system.out.println(); input.nextline(); } catch (exception e1) { system.out.println(e1.getmessage()); system.out.println(); input.nextline(); }
Comments
Post a Comment