3
I’m trying to run this code in Java, using Eclipse. The same runs once normal. When trying to repeat the operation (choosing option 1) gives error as shown below.
If I remove the scanner.close()
; it works normal by running several times.
I’ve found something about it on the Internet, including here, but I didn’t understand and I couldn’t solve the problem.
Someone could help by clarifying why the error occurs and how to resolve the error?
import java.util.Scanner;
public class Exercicio{
public int menu() {
Scanner scanner = new Scanner(System.in);
int opcao;
System.out.println("ESCOLHA UMA OPÇÃO:");
System.out.print("1-Imprime opção escolhida\n0-Sair\nOpção:");
opcao = scanner.nextInt();
scanner.close(); //ERRO AQUI. SE REMOVER ESTA LINHA, FUNCIONA.
return opcao;
}
public static void main (String[] args) {
int opcao;
Exercicio exercicio = new Exercicio();
do {
opcao = exercicio.menu();
switch (opcao) {
case 0 :
break;
case 1 :
System.out.println("Você escolheu a opção 1.\n");
break;
}
}while (opcao != 0);
}
}