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 3In 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.
3 Answers
The first code reads the input in a while loop - i.e. until it finds in.hasNext() == false.
The second code is using an if condition - it reads in.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:
- It will fail for empty input.
- It is a code duplication with the content of the while loop.
its not about in.next() the problem is with using if it gets executed only once and about next() it only returns the next token
so in 2nd case:(if one) when you enter member technical staff at this part : String desg = in.next(); only member is assigned to desg and after it enters if it checks for the next token (which is technical) and concatenates it with the previous string desg+=in.next() so now desg becomes membertechnical
If you want to learn more details about a class in API, javadoc is best source. Here is javadoc for Scanner.
public String next() 1Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.