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
Related
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.
I am a beginner in java programming. I have a question on whats going on, whenever i try to compile it, it keeps giving me error like this :
Exception in thread "main" java.util.InputMissMatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at MoreUserInputOfData.main(MoreUserInputOfData.java:28)
if someone would like to help me clean up my code as well, it wouldn't hurt..
import java.util.Scanner;
public class MoreUserInputOfData{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String firstName, lastName, loginName;
int grade, studentID;
double gpa;
System.out.println("Please enter the following information, so i cann sell it for a profit!");
System.out.print("First name: ");
firstName = keyboard.next();
System.out.print("Last name: ");
lastName = keyboard.next();
System.out.print("Grade (9-12): ");
grade = keyboard.nextInt();
System.out.print("Student ID: ");
studentID = keyboard.nextInt();
System.out.print("Login: ");
loginName = keyboard.next();
System.out.print("GPA (0.0-4.0): ");
gpa = keyboard.nextDouble();
System.out.println("");
System.out.println("Your information:");
System.out.println("Login:"+loginName);
System.out.println("ID: "+studentID);
System.out.println("Name: "+lastName+", "+firstName);
System.out.println("GPA: "+gpa);
System.out.println("Grade: "+grade);
}
}
Look at your code at line 28. When you input data, maybe you input the wrong type that the variable can't accept. For example: nextDouble require dot like 0.3 but you input 3.
For nextDouble : InputMismatchException -- if the next token does not match the Float regular expression, or is out of range
you should write it by prevent exception like:
// find the next double token and print it
// loop for the whole scanner
while (keyboard.hasNext()) {
...
// if the next is a double, print found and the double
System.out.print("GPA (0.0-4.0): ");
if (keyboard.hasNextDouble()) {
gpa = keyboard.nextDouble();
} else {
System.out.print("Not double");
}
...
}
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.
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++;
}
}
I am working on this airline program. The program should ask the user how many seats on the plane are sold and then I have this for loop to allow a user to enter a name and a meal choice for each person on the plane.
I have tried reading through some different questions about infinite for loops on stackoverflow, but I can't seem to figure out exactly what is going wrong with my code. I feel like there must be something about for loops that I am not understanding because I thought that it would only go through until your i < someNumber is no longer true.
So when I run this program, say I enter 2 seats I would expect it to go through the loop just twice, but It just keeps going. asking for a name and then a meal.
import java.util.Scanner;
public class Flyers
{
String name;
String mealType;
int economySeats;
int businessSeats;
int firstClassSeats;
int count;
public Flyers()
{
}
public String toString()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
return "Name: " + name + ", Meal " + mealType;
}
public void addEconomyFlyers()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
economySeats = in.nextInt();
for(count = 0; count < economySeats; count++)
{
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
}
}
Here is my main class if that is helpful.
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Flyers newFlyers = new Flyers();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
newFlyers.addEconomyFlyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
remove below code from toString()
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
You are already reading these from the for loop.
Also, your do-while loop is all wrong. The condition doesn't make sense. It should be option > 0 && option <4
As Pat said:
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
this code in the toString() is obsolete
however the do while does make sense, to me at least, as i see it you want the menu printed out each time the user gives an invalid int, however you are still letting 0 get through although that is not a valid choice, the do while should be:
while (option <= 0 || option > 4);
or
while (option < 1 || option > 4);
Another quirk in your code:
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
you create a new instance of the class you have just modified and call toString() on, even though you have not populated that class with data, so the toString method as it would be after the edit pat suggested will return "Name: Meal "
As i see your code is a work in progress, try adding more System.out.print on various variables for debugging purpose or use a debugger, though i know using debugger when learning can be difficult, it sure was for me. Also remember that every time you create a new instance ex:
Flyers newFlyer = new Flyers();
it has only the data that is either set by default or set in your constructor ex:
public Flyers()
{
}
I hope what i wrote was helpful, have a nice day and keep at it.