NoSuchElementException error when capturing data entry with Scanner

I'm having problems with data entries using the Scanner with JOptionPane works fine.

Exception in thread "main" java.util.NoSuchElementException

  at java.util.Scanner.throwFor(Unknown Source)
  at java.util.Scanner.next(Unknown Source)
  at java.util.Scanner.nextInt(Unknown Source)
  at java.util.Scanner.nextInt(Unknown Source)
  at pkgClientesPedidosDiogoVinicius.TesteClientesPedidos.menu(TesteClientesPedidos.java:43)
  at pkgClientesPedidosDiogoVinicius.TesteClientesPedidos.main(TesteClientesPedidos.java:18)
import java.io.IOException;

import java.util.Scanner;


public class TesteClientesPedidos {

    static int opcao;

    public static void main(String[] args) throws IOException {
        menu();

    }

    static void menu() throws IOException {

        Scanner leitura = new Scanner(System.in);
        do {
            System.out.println("PROGRAMA CLIENTES/PEDIDOS - OPÇÕES\n");
            System.out.println("----------------------------------\n");
            System.out.println("1  - Cadastrar Gerente\n");
            System.out.println("2  - Cadastrar Vendedor\n");
            System.out.println("3  - Cadastrar Técnico\n");
            System.out.println("4  - Mostrar dados dos funcionarios(Gerente/Vendedor/Técnico\n");
            System.out.println("5  - Cadastrar Item de Pedido\n");
            System.out.println("6  - Cadastrar Pedido\n");
            System.out.println("7  - Mostrar Dados de Pedido e Item de Pedido\n");
            System.out.println("8  - Cadastrar Gerente Administrativo\n");
            System.out.println("9  - Cadastrar Gerente Financeiro\n");
            System.out.println("10 - Mostrar dados de Gerente Administrativo e Financeiro\n");
            System.out.println("11 - Mostrar cálculo do salário para cada funcionario (Gerente/Vendedor/Técnico\n");
            System.out.println("12 - Sobre\n");
            System.out.println("13 - Encerrar programa\n");

            System.out.println("Informe a opção:");
            opcao = leitura.nextInt();
            switch (opcao) {
            case 1:
                cadastrarGerente();
                System.out.println(">>PROGRAMA");
                break;
            case 13:
                System.out.println(">>PROGRAMA FINALIZADO");
                break;
            }

        } while (opcao != 13);
        leitura.close();
    }

    public static void cadastrarGerente() {

        String nome;
        int matricula;
        String telefone;
        String email;
        String cidade;
        String estado;
        double salario;
        double taxaVenda;

        Scanner entrada = new Scanner(System.in);

        System.out.println("CADASTRAR GERENTE\n");
        System.out.println("Nome:........:");
        nome = entrada.nextLine();

        System.out.println("Matricula:...:");
        matricula = entrada.nextInt();

        System.out.println("Telefone:....:");
        telefone = entrada.next();

        System.out.println("Cidade:......:");
        cidade = entrada.nextLine();
        entrada.next();

        System.out.println("E-mail:......:");
        email = entrada.nextLine();
        entrada.next();

        System.out.println("Salário:.....:");
        salario = entrada.nextDouble();

        System.out.println("Estado:......:");
        estado = entrada.nextLine();
        entrada.next();

        Gerente g1 = new Gerente(nome, matricula, telefone, email, cidade, estado, salario);

        try {
            System.out.println("Taxa Venda:..:");
            taxaVenda = entrada.nextDouble();
            g1.setTaxaVenda(taxaVenda);

        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        entrada.close();

    }
}
Author: Diogo Lopes, 2017-06-02

1 answers

The problem is that you are manipulating two variables for data entry, and you are closing the second one. Only by doing entrada.close();, you are terminating the data entry(the System.in) and not just the variable.

With this, when trying to return to the menu, bursts this exception in the Line opcao = leitura.nextInt();, because you have already terminated the System.in, which is responsible for the input of data in java globally, including in the variable leitura, opened in your main.

One of the possible solutions without changing too much code is to work only with a variable Scanner, and use it to capture all the entries of this class:

import java.io.IOException;
import java.util.Scanner;

public class TesteClientesPedidos {

    static int opcao;
    static Scanner leitura = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        menu();

    }

    static void menu() throws IOException {

        do {
            System.out.println("PROGRAMA CLIENTES/PEDIDOS - OPÇÕES\n");
            System.out.println("----------------------------------\n");
            System.out.println("1  - Cadastrar Gerente\n");
            System.out.println("2  - Cadastrar Vendedor\n");
            System.out.println("3  - Cadastrar Técnico\n");
            System.out.println("4  - Mostrar dados dos funcionarios(Gerente/Vendedor/Técnico\n");
            System.out.println("5  - Cadastrar Item de Pedido\n");
            System.out.println("6  - Cadastrar Pedido\n");
            System.out.println("7  - Mostrar Dados de Pedido e Item de Pedido\n");
            System.out.println("8  - Cadastrar Gerente Administrativo\n");
            System.out.println("9  - Cadastrar Gerente Financeiro\n");
            System.out.println("10 - Mostrar dados de Gerente Administrativo e Financeiro\n");
            System.out.println("11 - Mostrar cálculo do salário para cada funcionario (Gerente/Vendedor/Técnico\n");
            System.out.println("12 - Sobre\n");
            System.out.println("13 - Encerrar programa\n");

            System.out.println("Informe a opção:");
            opcao = leitura.nextInt();
            leitura.nextLine();
            switch (opcao) {
            case 1:
                cadastrarGerente();
                System.out.println(">>PROGRAMA");
                break;
            case 13:
                System.out.println(">>PROGRAMA FINALIZADO");
                break;
            }

        } while (opcao != 13);
        leitura.close();
    }

    public static void cadastrarGerente() {

        String nome;
        int matricula;
        String telefone;
        String email;
        String cidade;
        String estado;
        double salario;
        double taxaVenda;

        System.out.println("CADASTRAR GERENTE\n");
        System.out.println("Nome:........:");
        nome = leitura.nextLine();

        System.out.println("Matricula:...:");
        matricula = leitura.nextInt();

        System.out.println("Telefone:....:");
        telefone = leitura.next();

        System.out.println("Cidade:......:");
        cidade = leitura.nextLine();
        leitura.next();

        System.out.println("E-mail:......:");
        email = leitura.nextLine();
        leitura.next();

        System.out.println("Salário:.....:");
        salario = leitura.nextDouble();

        System.out.println("Estado:......:");
        estado = leitura.nextLine();
        leitura.next();

        Gerente g1 = new Gerente(nome, matricula, telefone, email, cidade, estado, salario);

        try {
            System.out.println("Taxa Venda:..:");
            taxaVenda = leitura.nextDouble();
            g1.setTaxaVenda(taxaVenda);

        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Notice that you have a leitura.nextLine() right after picking up the option, and this is to not let the space escape and skip one of the data entries, if the chosen option is 1. But this is not the recommended solution, I recommend that you take a read in this answer, that has a better guidance of how to avoid this type of escape.

 3
Author: , 2017-10-03 17:01:41