1
public class Test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(sc.hasNext()) {
            System.out.println("First name: ");
            String fname =sc.next();
            System.out.print("Last name: ");
            Lname = sc.next();

        }


}

I'm just a beginner at java, hope someone can help me out please. Ignore the last print line i used it so i could understand what exactly i can ouptut. without the while loop i get the correct output i expect of the code, but once i add the while(sc.hasnext)
a scanner comes before the first name and ignores the scanner that used to input the first name. Does the hasNext() skip scanner?

1
  • thank you soo much for those who answered my problem... due to personal reasons i removed some parts of the code... Commented Nov 18, 2017 at 17:12

2 Answers 2

3

From the documentation of Scanner.hasNext():

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

This means that the while loop which you add will wait until you write something. After you write something, it will be read for first name and it will continue on. When you fill all the data it will wait again to write something and basically loop for ever.

You need other condition for the loop. For example you can use do while and after last data is written, you can ask the user additional question whether he wants to add something else. E.g:

do {
  // gather data
  System.out.println("Continue ?");
  String c = scanner.next();
} while("yes".equals(c))
Sign up to request clarification or add additional context in comments.

1 Comment

String c should be declared before loop if you want to use it in loop condition.
1

It's not actually ignoring or skipping the scanner for first name (variable fname), but in your case, when the hasNext() function runs, it puts the input in the buffer and transfers it to the immediate sc.next() or sc.nextLine() (if any of them exists).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.