Reputation: 11
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!");
}
Upvotes: 1
Views: 1161
Reputation: 191701
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!");
Upvotes: 1
Reputation: 3166
After removing PETCScanner.close();
I ran your code, and I don't get any errors. I get this:
Are you a Producer or a Consumer?\\n (P = Producer, C = Consumer
Neither
Sorry try Again
O
O
You're Done!
Upvotes: 0
Reputation: 1622
I saw that the exception was thrown from the calling ProducerOrConsumer.nextLine()
.
There was no element found as the result == null
. You can have a look more detailed in the java.util.Scanner.nextLine()
public String nextLine() {
...
if (result == null)
throw new NoSuchElementException("No line found");
...
if (result == null)
throw new NoSuchElementException();
...
}
Best,
Upvotes: 0