Java: Try to Understand Getting Inputs from Users Using Scanner -


i have programs , few questions regarding how .next(), .nextint(), .hasnext() , .hasnextint() of scanner class work. thank in advance of :)

import java.util.scanner;  public class test {      public static void main (string[] args) {     scanner console = new scanner(system.in);     int age;     system.out.print("please enter age: ");     while (!console.hasnextint()) {             system.out.print("please re-enter age: ");             console.next();         }     age = console.nextint();     system.out.println("your age "+age);     }   } 

1/ when !console.hasnextint() executed first time, why ask input?

i thought @ first console empty, !console.hasnextint() true (empty not int), should go directly "please enter age: " "please re-enter age: " thought seems wrong.

here, user needs enter before "please re-enter age: " printed.

2/ data type of console.next() string (i tried making int s = console.next(); , gave error), why isn't infinite loop?

3/ instance, when comes console.next();, input 21. why age have value of 21? thought because of console.hasnextint(), need enter number, , new number value of age.

hasnextint() waits input string , tells if can converted int. in mind, let's go on questions:

when !console.hasnextint() executed first time, why ask input?

because blocks until there's input console.

the data type of console.next() string (i tried making int s = console.next(); , gave error), why isn't infinite loop?

because hasnextint() returns true when input can converted int, example "21".

for instance, when comes console.next();, input 21. why age have value of 21? thought because of console.hasnextint(), need enter number, , new number value of age.

calling next() doesn't wait new input, swallows input tested hasnextint() scanner can move on next one. have been first statement in loop, same effect.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -