Usando scanner.nextLine () [duplicado]

Esta pergunta já tem uma resposta aqui:

@Scanner está pulando nextLine () depois de usar next () ou nextFoo ()? 15 respostas

Estou com problemas ao tentar usar o método nextLine () no java.util.Scanne

Aqui está o que eu tentei:

import java.util.Scanner;

class TestRevised {
    public void menu() {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a sentence:\t");
        String sentence = scanner.nextLine();

        System.out.print("Enter an index:\t");
        int index = scanner.nextInt();

        System.out.println("\nYour sentence:\t" + sentence);
        System.out.println("Your index:\t" + index);
    }
}

Exemplo 1 Este exemplo funciona como pretendido. A linhaString sentence = scanner.nextLine(); aguarda a entrada da entrada antes de continuar emSystem.out.print("Enter an index:\t");.

Isso produz a saída:

Enter a sentence:   Hello.
Enter an index: 0

Your sentence:  Hello.
Your index: 0
// Example #2
import java.util.Scanner;

class Test {
    public void menu() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nMenu Options\n");
            System.out.println("(1) - do this");
            System.out.println("(2) - quit");

            System.out.print("Please enter your selection:\t");
            int selection = scanner.nextInt();

            if (selection == 1) {
                System.out.print("Enter a sentence:\t");
                String sentence = scanner.nextLine();

                System.out.print("Enter an index:\t");
                int index = scanner.nextInt();

                System.out.println("\nYour sentence:\t" + sentence);
                System.out.println("Your index:\t" + index);
            }
            else if (selection == 2) {
                break;
            }
        }
    }
}

Exemplo # 2: Este exemplo não funciona como pretendido. Este exemplo usa um loop while e uma estrutura if - else para permitir que o usuário escolha o que fazer. Quando o programa chegar aString sentence = scanner.nextLine();, não espera pela entrada, mas executa a linhaSystem.out.print("Enter an index:\t");.

Isso produz a saída:

Menu Options

(1) - do this
(2) - quit

Please enter your selection:    1
Enter a sentence:   Enter an index: 

O que torna impossível inserir uma frase.

Por que o exemplo 2 não funciona como o esperado? A única diferença entre Ex. 1 e 2 é esse Ex. 2 tem um loop while e uma estrutura if-else. Não entendo por que isso afeta o comportamento do scanner.nextInt ().

questionAnswers(5)

yourAnswerToTheQuestion