maddie pattie c :
So I'm working on this energy tree project for my computer programming class, I was trying to make a do-while loop that asked the user if they were a producer or consumer and if any other input was entered loop would start over. My code keeps getting the error
"java.util.NoSuchElementException" on line 45
where it says
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 :
It seems you are closing a Scanner, which closes all attached resources. When trying to read again, you have "no such element" to read.
You only need one scanner per application, there is no need to re-create one, too.
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!");
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=358834&siteId=1