I am using Scanner class to take input. I am trying to get all the
words in a line using in.next(). I know it can be done using
nextLine() but i want to understand how in.next() and in.hasNext()
works.
System.out.println("What is designation");
String desg = in.next();
while(in.hasNext()){
desg+=in.next();
}
Gives out put as
What is designation
member technical staff\n
^Z
Hello abhishek kumarNext year you will be 22Salary is 30000.0Designation is membertechnicalstaff
But if i use
System.out.println("What is designation");
String desg = in.next();
if(in.hasNext()){
desg+=in.next();
}
It gives output as
What is designation
member technical staff
Hello abhishek kumarNext year you will be 22Salary is 44254.0Designation is membertechnical
In the first case i am getting all the words but it keeps asking for
next input and i have to specify end of input using CTRL+Z. But in
second case i am not getting the last word(staff). Please explain.
The first code reads the input in a
whileloop – i.e. until it findsin.hasNext() == false.The second code is using an
ifcondition – it readsin.next()at most once (after the initial read).Thus, the second code is not “waiting for new input” because it simply asks for
in.next()only once, and not until input is exhausted, unlike the second code snap.P.S. Note that the line
String desg = in.next();(in the first code snap) is a bad practice for two reasons: