Problem with nextLine() after nextInt() in a Loop

Asked

Viewed 1,031 times

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 (Wishes 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 capture user input in second question?

  • Could you elaborate on the problem? I couldn’t understand your description.

1 answer

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.