checking if input from scanner is int with while loop java -


i want following while loop check if input integer. cannot contain decimals because pointing array. if value entered decimal should prompt user again. problem 2 prompts before while loop starts code. ideas?

      system.out.print("enter month (valid values 1 12): ");     scanner monthscan = new scanner(system.in);     int monthinput = monthscan.nextint();     // if month input below 1 or greater 12, prompt value     while(monthinput<1 || monthinput>12 || !monthscan.hasnextint())     {         system.out.print("invalid value! enter month (valid values 1 12): ");         monthinput = new scanner(system.in).nextint();     } 

thanks

edit: current output gives following:

enter month (valid values 1 12): 2 2 

notice how had enter 2 twice though valid value.

a small modification program solves problem

 system.out.print("enter month (valid values 1 12): ");         scanner monthscan = new scanner(system.in);        int monthinput = monthscan.nextint();         // if month input below 1 or greater 12, prompt value         while((monthinput<1 || monthinput>12) )         {             system.out.print("invalid value! enter month (valid values 1 12): ");              monthinput = monthscan.nextint();         }         system.out.println("i here"); 

output:

enter month (valid values 1 12): -5 invalid value! enter month (valid values 1 12): -5 invalid value! enter month (valid values 1 12): -2 invalid value! enter month (valid values 1 12): 5 here 

hope helps you.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -