Problem with nextLine () after nextInt () on a Loop [closed]

1

I have this code to remove from a ArrayList , and a while to check if the user wants to continue removing elements. But when the remove value is true the logic "skips" the next question ( Do you want to continue? ).

package AList;

import java.util.*;

public class Principal {

    public static void main(String[] args) {

        List<String> agenda = new ArrayList<>();

        Scanner entrada = new Scanner(System.in);
        int pos = 0;
        String opcao;
        agenda.add("Cachorro, 12345");
        agenda.add("Doido, 54321");

        int n = agenda.size(); //pega o tamanho
        for (int i = 0; i < n; i++) {
            System.out.printf("Agenda pos %d = %s\n", i, agenda.get(i));
        }

        do {
            System.out.println("Digite o elemento para remover: ");

            try {
                pos = entrada.nextInt();
                agenda.remove(pos);
            } catch (InputMismatchException e) {
                System.out.println("Erro " + e);
            } catch (IndexOutOfBoundsException e) {
                entrada.nextLine();
                System.out.println("Erro: " + e);
            }

            System.out.println("Deseja continuar? ");
            opcao = entrada.nextLine();
        } while (!opcao.equals("n"));

        int i = 0;
        for (String contatos : agenda) {
            System.out.printf("Agenda pos %d: %s", i, contatos);
            i++;
        }
    }
}

How do I get the user input in the second question?

    
asked by anonymous 18.10.2016 / 01:05

1 answer

1

The problem is that the nextInt() method does not consume the user-entered line break. You need to discard it before calling nextLine() again:

pos = entrada.nextInt();
entrada.nextLine(); // Descarta quebra de linha
agenda.remove(pos);

Font : SOen - Scanner is skipping nextLine () after using next (), nextInt () or other nextFoo () methods

    
02.11.2016 / 13:03