Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at ShoppingCartManager.printMenu(ShoppingCartManager.java:24)
at ShoppingCartManager.main(ShoppingCartManager.java:15)
My code issue seems to be in line 24 and 15 of my codes and I spend hours trying to fix it please help.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter Customer's Name:");
String customerName = scnr.nextLine();
System.out.println("Enter Today's Date:");
String currentDate = scnr.nextLine();
ShoppingCart shopCart = new ShoppingCart(customerName, currentDate);
System.out.println();
System.out.println("Customer Name: "+ shopCart.getCustomerName());
System.out.println("Today's Date: "+ currentDate);
System.out.println("");
printMenu(shopCart); // LINE 15
}
public static void printMenu(ShoppingCart shopCart) {
while(true) {
System.out.println("MENU\na - Add item to cart\nd - Remove item from
cart\nc - Change item quantity\ni - Output items' descriptions\no -
Output shopping cart\nq - Quit\n\nChoose an option:");
Scanner scnr = new Scanner(System.in);
char ch = scnr.next().charAt(0); // LINE 24
scnr.nextLine();
if(ch == 'a' || ch == 'A' ) {
System.out.println("ADD ITEM TO CART");
System.out.println("Enter Item Name: ");
String name = scnr.nextLine();
System.out.println("Enter Item Description: ");
String itemDescritpion = scnr.nextLine();
System.out.println("Enter Item Price: ");
int itemPrice = scnr.nextInt();
System.out.println("Enter Item Quantity: ");
int quantity = scnr.nextInt();
scnr.nextLine();
ItemToPurchase item = new ItemToPurchase(name, itemDescritpion,itemPrice, quantity);
shopCart.addItem(item);
}
This is a OnlineShoppingCart problem and it works on eclipse but doesnt work on the online website that I'm trying to submit to. I tried converting the char ch = scnr.next().charAt(0); scnr.nextLine(); to String a = sncr.nextLine(); char ch = a.charAt(0); but that doesnt work either and still gives me the same error at the start.
Related
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I have a class Test with a static method to take input.
class Test {
public static Student readStudent() throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
System.out.println("Enter age of student");
int age = s.nextInt();
s.close();
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}
}
I am able to take the input for one student but once i put it in a for loop i get a java.util.NoSuchElementException: No line found error.
This is my loop
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent();
}
Why am I getting this error? Thanks.
s.close(); closes the current Scanner object, but also all underlying streams, which is System.in in this case. Once your standard input stream is closed, you cannot open it anymore.
So all in all it would be best to close your Scanner after you're sure you won't need it anymore and restructure your code like this:
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent(sc);
// do something with your student object here
}
sc.close();
And change your method to
public static Student readStudent(Scanner s) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
s.nextLine(); // Need to consume new line
System.out.println("Enter age of student");
int age = s.nextInt();
s.nextLine(); // Need to consume new line
// no closing here
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}
I am trying to write a Java program in which the user specifies how many "student records" they would like to input, followed by the student's name, age, and GPA, which then gets stored as text. However, I am having a problem with my text not including all entered data and a mysterious dangling newline that I cannot get rid of.
Here is my program:
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:\\Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
Here is sample input and output to illustrate my issues:
run:
How many student records would you like to enter: 3
Enter Name: Jon
Enter Age: 20
Enter GPA: 3.4
Enter Name: Bill
Enter Age: 24
Enter GPA: 3.6
Enter Name: Ted
Enter Age: 34
Enter GPA: 3.9
This is the produced text file:
20
3.4
Bill
24
3.6
Ted
34
3.9
Why doesn't it store the first name entered? Why isn't there a newline in the first entry, but it is in the others?
The problem is that you're using nextLine() when you need to be using next(). I'm assuming you put the second input.nextLine() in there because you were initially having a problem where it would print out "Enter Name: " and then immediately "Enter Age: ". nextLine() is telling your program to skip whatever is there, and not to wait for it. The reason that this paradigm worked at all for any of your entries is that you put next = input.nextLine() at the bottom of your loop. Here's a fix:
package createfile;
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.next();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
You could also just move your input.nextLine() above name=input.nextLine() and it would have the same effect.
The other examples only work if you don't have names like "James Peter" - in their code examples only James would be saved as name.
I'd prefer this:
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
input.nextLine();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
This is the corrected for loop:
for ( int x = 1; x <= hm; x++ )
{
System.out.print( "Enter Name: " );
name = input.next();
input.nextLine();
System.out.print( "Enter Age: " );
age = input.nextInt();
input.nextLine();
System.out.print( "Enter GPA: " );
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println( name );
StudentFile.println( age );
StudentFile.println( gpa );
}
Some things you may want to consider:
Handle the IOException - it should not be ignored!!
Use the methods hasNextXXX() of the Scanner to check if something is available.
Refactor your usage of the variable next, it's never really used.
It's not necessary to call System.exit( 0 ) from the main method - rather use the return statement with a meaningful value.
when i use s.charAt(0) while s is an string input from the user, I get this as an error even though the program runs the first half of the program.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at Shopping.main(Shopping.java:22)
What's the solution to this program? here is my code.
import java.util.Scanner;
public class Shopping {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Programmed by Raymond Lee");
System.out.println("Welcome to Shopper's Paradise");
ShoppingCart cart = new ShoppingCart();
System.out.print("Enter the name of the first item: ");
String item = keyboard.nextLine();
System.out.print("Enter the quantity: ");
int quantity = keyboard.nextInt();
System.out.print("Enter the price: ");
double price = keyboard.nextDouble();
cart.addToCart(item, price, quantity);
System.out.print("Enter the name of the next item or Q to quit: ");
String quit = keyboard.nextLine();
char choice = quit.charAt(0);
while((choice != 'Q' && choice != 'q') || quit.length() != 1) {
quit = item;
System.out.print("Enter the quantity: ");
quantity = keyboard.nextInt();
System.out.print("Enter the price: ");
price = keyboard.nextDouble();
cart.addToCart(item, price, quantity);
System.out.print("Enter the name of the next item or Q to quit: ");
quit = keyboard.nextLine();
choice = quit.charAt(0);
}
System.out.println(cart);
}
}
The error is occuring at this line
char choice = quit.charAt(0);
This is due to the fact that when you call
double price = keyboard.nextDouble();
then nextDouble leaves the newline in the input stream. So when following is called
String quit = keyboard.nextLine();
then result of nextLine is empty string, results in the given error when you try to use charAt method.
To resolve this error, simply change following
String quit = keyboard.nextLine();
To
String quit = keyboard.next();
Hope this helps
I'm trying to write a progam that prompts the user to enter the number of students followed by prompting for username and grade. It runs once (meaning I get asked the number of students, I can enter the first name and number), and then it gives an InputMismatchException.
Can you see what's wrong?
public class LowestScore {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
}
Error
run: Enter the number of students12 Enter student name Enter grade josje 8
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
demo.LowestScore.main(LowestScore.java:31) Java Result: 1
You need to catch the carriage return after each of the nextInt call.
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
input.nextLine(); // catch it
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
input.nextLine(); // catch it
}
Notice that you can still run into an exception if you enter an invalid Integer.
Edit:
Basicly the nextInt catches a number that you do input, but it doesn´t catch the carriage return (the new line you are creating by pressing enter). So what it does is, you enter a number for the amount of students, lets say 1. The nextLine call instantly gets the carriage Return, creates an empty Student name and you jump straight forward to the next nextInt call. This goes on until you reach the complet amount of students. Calling nextLine after the nextInt catches the carriage return, and you are able to input the student Name.
You can specifically notice this at the point where it does print
Enter student name
Enter grade
at the same time. You allways jump directly to the next input for an Integer.
Edit2:
if you would like to catch the Exception for a wrong input aswell, then you could do it like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfStudents = -1;
boolean exception = true;
do {
try {
System.out.print("Enter the number of students");
numberOfStudents = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
int number = 0;
while (number <= numberOfStudents) {
exception = true;
number++;
System.out.println("Enter student name");
String studentName = input.nextLine();
int grade;
do {
try {
System.out.println("Enter grade");
grade = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
// input.nextLine();
}
}
Check out this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number < numberOfStudents) {
String num = input.nextLine();
System.out.println("Enter student name");
String studentName = input.next();
System.out.println("Enter grade");
int grade = Integer.parseInt(input.next());
number++;
}
}