Java scanner class no such element exception error [duplicate] - java

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);
}

Related

How can I get rid of the very last letter of the last letter of a reversed string?

Hi I have a password generator and I have it mostly figured out. The only issue I am having is that when I print out my reversed string instead of printing the 2nd to last like I need. But it prints both of the last 2 letters of the first name. Here is the code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first name here: ");
String fname = input.next();
System.out.println("enter middle name here: ");
String mname = input.next();
System.out.println("Enter last name here: ");
String lname = input.next();
System.out.println("Enter birthday (MMDDYYYY) here: ");
int age = input.nextInt();
lname = lname.substring(lname.length()-3);
char resultfn = fname.charAt(1);
char resultmn = mname.charAt(2);
fname = fname.substring(fname.length()-2);
System.out.print(resultfn);
System.out.print(resultmn);
System.out.print(lname);
System.out.print(fname);
}
}
Ok so I figured it out what i did was add a new line of code which was
char reversedfn = fname.charAt(0);
after I did that it worked great!
I put it after the
fname = fname.substring(fname.length()-2);
and then had it print out the reversedfn line and it came out to the letter i needed. So it now looks like this.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first name here: ");
String fname = input.next();
System.out.println("enter middle name here: ");
String mname = input.next();
System.out.println("Enter last name here: ");
String lname = input.next();
System.out.println("Enter birthday (MMDDYYYY) here: ");
int age = input.nextInt();
lname = lname.substring(lname.length()-3);
char resultfn = fname.charAt(1);
char resultmn = mname.charAt(2);
fname = fname.substring(fname.length()-2);
char reversedfn = fname.charAt(0);
System.out.print(resultfn);
System.out.print(resultmn);
System.out.print(lname);
System.out.print(reversedfn);
}
}

Read file into string by separating words by tab

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.

Java runtime exception - "java.util.NoSuchElementException"

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.

what is the solution to StringIndexOutOfBoundsException

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

input mismatch exception error student grade and name

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++;
}
}

Categories