This program runs just fine, but for some reason when I ask for an input for name it will only save the first word in the response. For example if I enter "Jon Snow" when I use it later for output it will only show "Jon".
import java.util.Scanner;
public class help
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in); //object for user input
//constant
final double tax = 0.08; //Sales tax
//variables
int choice; //menu selection/case switch
String name; //customer's name
String address; //customer's address
String email; //customer's email address
String item; //item purchased
double itemsPurchased; //number of items purchased
double itemPrice; //price of item purchased
double total; //total for purchase
double grandTotal; //total + tax
double taxAmount; //tax of the purchase
//Menu
System.out.println("1. Enter Customer Information");
System.out.println("2. Display Total Bill");
System.out.println("3. Quit\n");
System.out.print("Enter 1, 2, or 3 to make your selection: ");
choice = input.nextInt();
switch(choice){
//Customer info
case 1:
//inputting info
System.out.println("\nPlease enter the customers information.");
//name
System.out.print("Name: ");
name = input.next();
input.nextLine();
//address
System.out.print("Address: ");
address = input.nextLine();
//email
System.out.print("Email Adress: ");
email = input.next();
input.nextLine();
//reading info back to user
System.out.println("\nThe customer has successfully been added to our list with the following information: ");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Emal: " + email);
break;
//Customer receipt
case 2:
//name
System.out.println("");
System.out.print("Enter customer's name: ");
name = input.next();
input.nextLine();
//name of item purchased
System.out.print("Enter item purchased: ");
item = input.next();
input.nextLine();
//number of items purchased
System.out.print("Number of items purchased: ");
itemsPurchased = input.nextDouble();
input.nextLine();
//price of item
System.out.print("Price of item: ");
itemPrice = input.nextDouble();
input.nextLine();
//defining taxAmount, total, and grandTotal
total = (itemPrice * itemsPurchased);
taxAmount = (total*tax);
grandTotal = total + taxAmount;
//bill
System.out.println("");
System.out.println(name);
System.out.println("");
System.out.printf("%-20s %-15s %-15s\n", "Product Purchased", "Quantity", "Total Cost");
System.out.println("");
System.out.printf("%-20s %-15s %-15s\n", item, itemsPurchased, total);
System.out.println("");
System.out.printf("%-20s %-15s %-15s\n", "Tax(#8%):", "", taxAmount);
System.out.printf("%-20s %-15s %-15s\n", "Total Cost:", "", grandTotal);
break;
//Quit
case 3:
System.out.println("End Program");
break; //void
//Default statement
default:
System.out.print("Invalid value entered.");
}//end case
}//end main
}//end class
name = input.nextLine()
You are not reading the whole line but only the first word.
For the Scanner class, the next() function reads the next tokenized input while nextLine() retrieves the whole line until the carriage return (\n).
Eg. "happy days again"
next() // "happy"
next() // "days"
next() // "again"
or,
nextLine() // "happy days again"
EDIT: Try the code below
input.nextLine(); // IMP: To get the carriage return after choice is typed
//name
System.out.println("");
System.out.print("Enter customer's name: ");
name = input.nextLine();
//name of item purchased
System.out.print("Enter item purchased: ");
item = input.nextLine();
Try this,
Using next() will give you the 1st Word, but if you want the whole line use nextLine().
name = input.nextLine();
eg:
Scanner scan = new Scanner(System.in);
name = input.nextLine();
Related
I am just a beginner, so any help would be appreciated.
So here is my code:
import java.util.Scanner;
public class AccountScanner {
public static void main (String[] args) {
String name, course;
int age;
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter age: ");
age = input.nextInt();
System.out.print("Enter Course: ");
course = input.next();
System.out.println();
System.out.println("Name:" +name);
System.out.println("Age:" +age);
System.out.println("Course:" +course);
System.exit(0);
}
}
but what if the user did enter one of the details. What can I do to make it display "Not Available" instead
example:
enter name: Zack
enter age:
enter course: BSCS
output would be:
Name: Zack
Age: Not available
Course: BSCS
You can use a conditional operator to check if the inputs are empty and show the result correspondingly as follows:
String name, course, age;
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter age: ");
age = input.nextLine();
System.out.print("Enter Course: ");
course = input.nextLine();
System.out.println();
System.out.println("Name:" +(name.isEmpty()?"Not Available":name));
System.out.println("Age:" +(age.isEmpty()?"Not Available":new Integer(age)));
System.out.println("Course:" +(course.isEmpty()?"Not Available":course));
System.exit(0);
We are required to complete a simple ticketing system for a local cinema in netbeans and I'm stumped on two problems.
Problem 1 is as part of the output, is once you have selected ticket type + quantity, there needs to be an output "you are purchasing X number of tickets at Y quantity"
Problem 2 is the seniors ticket needs to be at a cost of $32.50 and I cannot seem to find a workaround for allowing a calculation to be made using a decimal figure. I debugged and it seemed to change the number to an integer, which then would not calculate correctly. Help!
package ticketingsystem;
import java.io.*;
public class ticketingsystem
{
public static void main(String []args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String order,again;
int quantity,price1=0,price2=0, price3=0,loop1=0,quantity1,quantity2=0;
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do{
System.out.println(" ");
System.out.print("Enter your option: ");
order=br.readLine();
if (order.equalsIgnoreCase("1")) {
price1=18;
} else if (order.equalsIgnoreCase("2")) {
price1=36;
}
else if (order.equalsIgnoreCase("3")) {
price1= (int) 32.5;
}
System.out.print("Enter the number of tickets: ");
quantity1= Integer.parseInt(br.readLine());
quantity2=quantity1+quantity2;
price2=price1*quantity2;
System.out.println("You are purchasing " int (order=br) " tickets at" (quantity1);
System.out.print("Do you wish to continue? (Y/N) : ");
again=br.readLine();
if (again.equalsIgnoreCase("y"))
loop1=loop1+1;
else loop1=loop1-100;
} while (loop1==1);
System.out.println(" ");
System.out.println("Total Price : "+price2);
}
}
Hi would suggest to make the following changes.
First rename price2 to totalPrice and change it to a double:
double totalPrice;
I would create an enum class for TicketType, where you can also assign the price1 value:
enum TicketType {
child(18), adult(36), senior(32.5);
TicketType(double price) {
this.price = price;
}
private double price;
public double getPrice() {
return price;
}
}
You can now change you main method to this:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String order, again;
int quantity = 0;
double totalPrice;
TicketType ticketType; // add the enum to the method
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do {
System.out.println(" ");
System.out.print("Enter your option: ");
order = br.readLine();
//use a switch case instead of the if else pattern
switch (order.toLowerCase()) {
case "1":
ticketType = TicketType.child;
break;
case "3":
ticketType = TicketType.senior;
break;
default:
ticketType = TicketType.adult;
break;
}
System.out.print("Enter the number of tickets: ");
quantity = Integer.parseInt(br.readLine());
totalPrice += ticketType.getPrice() * quantity;
// %s will be replaced with the string value of ticketType, %.2f means it will be replaced with a decimal, round to decimals
System.out.printf("You are purchasing %s tickets at %.2f \n", ticketType, ticketType.getPrice());
System.out.print("Do you wish to continue? (Y/N) : ");
again = br.readLine();
}
while (again.equalsIgnoreCase("y"));
System.out.println(" ");
System.out.printf("Total Price : $%.2f \n", totalPrice);
}
You can use the System.out.printf() to format messages you print to the console
On the price1 value, you are losing some precision by storing it as an int.
In Java, the int is rounded (to floor) to values without the decimal point precision. For this purpose, you'll want to use float or double to retain your cent value.
Also, you may find the java.text.NumberFormat class useful for the Currency handling.
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
In this program, I'm creating 2 objects from the CarOrder class with preset values. I'm then asking the user for another 2 sets of values to create 2 more objects. Unfortunately, after entering tax status for the first one, it will skip letting the user enter a value for the buyer on the second one. Why is it randomly skipping this one question?
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter Buyer: ");
String buyer1 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car1 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
double cost1 = keyboard.nextDouble();
System.out.println("Enter quantity of cars being purchased: ");
int quantity1 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax1 = keyboard.nextBoolean();
System.out.println("Enter Buyer: ");
String buyer2 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car2 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
int cost2 = keyboard.nextInt();
System.out.println("Enter quantity of cars being purchased: ");
int quantity2 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax2 = keyboard.nextBoolean();
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2);
System.out.println("Chicago Car Wholesalers" );
System.out.println("Oct. 30th, 2012");
System.out.println("New Car Order Report");
}
}
I think nextBoolean() is consuming the boolean but leaving the end of line character, which your nextLine() then consumes as its input. So, add keyboard.nextLine() before asking for the second buyer.
keyboard.nextBoolean() reads only the boolean value. Now when you continue reading with keyboard.nextLine() you get Enter key (That's the skipping part you're talking about).
You need to add keyboard.nextLine(); after asking for the second buyer.
Maybe it's not skipping it, you're using the wrong buyer when creating "it". Look at this closely:
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2); // <-- This should be buyer2
In my tester file, I am trying to receive 3 inputs from the user however only 2 of the inputs are received and it seems that the program is skipping over the in.nextLine() line of code. Here is my code:
import java.util.Scanner;
public class IngredientTester
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*These 3 inputs work */
System.out.println("Please enter Ingredient name.");
String inputName = in.nextLine();
System.out.println("Please enter Ingredient measurement type.");
String inputType = in.nextLine();
System.out.println("Please enter Ingredient amount");
double inputAmount = in.nextDouble();
Ingredient inputIngredient = new Ingredient(inputName,inputType,inputAmount);
System.out.println(inputIngredient.getName() + "- " + inputIngredient.getAmount() + " " + inputIngredient.getMeasurement());
System.out.println("Please enter Ingredient name.");
inputName = in.nextLine();
/* ^ the input above does not work, but the ones below do work */
System.out.println("Please enter Ingredient measurement type.");
inputType = in.nextLine();
System.out.println("Please enter Ingredient amount");
inputAmount = in.nextDouble();
inputIngredient.setAmount(inputAmount);
inputIngredient.setName(inputName);
inputIngredient.setMeasurement(inputType);
System.out.println(inputIngredient.getName() + "- " + inputIngredient.getAmount() + " " + inputIngredient.getMeasurement());
}
}
The problem is that you are using:
double inputAmount = in.nextDouble();
which not only reads your first input amount but passes the carriage return to the next readLine statement.
The solution is to consume the carriage return first:
double inputAmount = Double.parseDouble(in.nextLine());