1
import java.util.Scanner;

public class mainClass{

    static public Scanner keyboard = new Scanner(System.in);

    public static void main (String [ ] args)
    {
        anotherMethod();
    }

    static public void anotherMethod()
    {
        String sentence;
        String answer;

        do{
            System.out.println("Lets read a sentence: ");
            String Sentence = keyboard.nextLine();
            System.out.println("The sentence read: " + sentence);

            System.out.println("Do you want to repeat?");
            answer = keyboard.next();

        } while (answer.equalsIgnoreCase("yes");
    }

}

The result is that after the first run, the program displays "Lets read a sentence:" and also "The sentence read: " without letting me enter a sentence..

I would like to know the simple way of solving this problem.

Fernando Carvalhosa
  • 1,098
  • 1
  • 15
  • 23
FocusFort
  • 19
  • 1
  • 4

2 Answers2

1

Here is what's happening: the program reads input with nextLine, then prompts for yes/no, at which point you type yes, and press Enter. Now Scanner's buffer contain these four characters:

'y' 'e' 's' '\n'

When you call next(), Scanner reads characters up to '\n' which serves as a delimiter. The letters are removed from the buffer, so "yes" becomes the result of next(). However, '\n' is not taken! It is left in the buffer for the next Scanner call.

Now the loop comes to its next iteration, your program prompts for more input, and calls nextLine(). Remember that '\n' in the buffer? That's what your program is going to read right away, ending the input.

You can fix this by replacing the call of next() with a call of nextLine().

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You need to use the nextLine() method for collecting your answer string as well.

answer = keyboard.nextLine();

Otherwise, the next() call only returns the string yes but leaves a new line character dangling behind that gets scanned at the next iteration of your while loop without giving you a chance to enter something.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89