maddie pattie c:
Então, eu estou trabalhando neste projeto árvore de energia para minha classe de programação de computador, eu estava tentando fazer um loop do-while que pediu o usuário se fossem um produtor ou consumidor e se qualquer outra entrada foi inserido laço seria começar de novo. Meu código mantém recebendo o erro
"java.util.NoSuchElementException" on line 45
onde diz
char Type = ProducerOrConsumer.nextLine().toUpperCase().charAt(0);
boolean isChoiceValid = false;
do
{
PETCScanner.close();
Scanner ProducerOrConsumer = new Scanner(System.in);
System.out.println("Are you a Producer or a Consumer?\\\\n (P = Producer, C = Consumer");
char Type = ProducerOrConsumer.nextLine().toUpperCase().charAt(0);
if (Type == 'P' || Type =='C')
{
}
else
System.out.println("Sorry try Again");
{
}
String Name = ProducerOrConsumer.nextLine().toUpperCase();
System.out.println(Name);
}while(isChoiceValid == (true));
System.out.println("You're Done!");
}
cricket_007:
Parece que você está fechando um scanner, que fecha todos os recursos ligados . Ao tentar ler novamente, você tem "nenhum elemento" para ler.
Você só precisa de um scanner de cada aplicação, não há necessidade de re-criar um, também.
Scanner sc = new Scanner(System.in);
boolean isChoiceValid = false;
do {
System.out.println("Are you a Producer or a Consumer?\\\\n (P = Producer, C = Consumer");
char type = sc.nextLine().toUpperCase().charAt(0);
if (type == 'P' || type =='C') {
boolean isChoiceValid = true;
} else {
System.out.println("Sorry try Again");
isValidChoice = false; // if you want
continue;
}
if (sc.hasNextLine()) {
String name = sc.nextLine().toUpperCase();
System.out.println(name);
}
} while(!isChoiceValid);
System.out.println("You're Done!");