java - Error: Integers added together in successive uses of scanner class -


i'm doing exercises related handling exceptions. while using scanner class , following exercises check inputmismatchexceptions, got following results following code.

static scanner sc = new scanner(system.in);  public static void main(string[] args){     system.out.print("enter integer: ");     int = getint();     system.out.print("enter second integer: ");     int b = getint();     int result = + b;     system.out.println(result); }  public static int getint(){     while (true){         try {             return sc.nextint();         }         catch(inputmismatchexception e){             system.out.print("i'm sorry, that's not integer."                     + " please try again: ");             sc.next();         }     } } 

the output was:

enter integer: 2 3 enter second integer: 5 

it seems if first calling of nextint() enter "2 3", or 2 integers space between them, next time nextint() called, receives first 2 integers added , halts program. going on here?

p.s. have tips me in formatting code in better way , making more organized other coders read?

when enter "2 3" (two integers space between them) scanner.nextint() pull in 2 , leave 3 still in scanner. now, when next nextint() called pull in 3 left without user having enter anymore data.

you can around using nextline() , check input string not contain spaces.

something this:

static scanner sc = new scanner(system.in);  public static void main(string[] args) {     system.out.print("enter integer: ");     int = getint();     system.out.print("enter second integer: ");     int b = getint();     int result = + b;     system.out.println(result); }  public static int getint() {     while (true) {         try {             string input = sc.nextline();             if (!input.contains(" ")) {                 int integer = integer.parseint(input);                 return integer;             } else {                 throw new inputmismatchexception();             }         } catch (inputmismatchexception | numberformatexception e) {             system.out.print("i'm sorry, that's not integer. please try again: ");         }     } } 

results:

enter integer: 2 3 i'm sorry, that's not integer. please try again: 2 enter second integer: 3 5 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -