I wrote the code to calculate the total based on the number of seats chosen by the user. The problem is when I enter a negative number for one of the seatings, the total is still calculated. Instead, when a negative number is inputted I want an error message to pop up and not calculate the total.
package javatheatreseating;
import java.util.Scanner;
public class JavaTheatreSeating {
public static final double PREMIUM_PRICE = 45.00;
public static final double STANDARD_PRICE = 30.00;
public static final double ECONOMY_PRICE = 21.00;
public static final double TAX_RATE = 0.0825;
public static final double SURCHARGE = 5.00;
public static void main(String[] args) {
int premiumSeats;
int standardSeats;
int economySeats;
double subTotal;
double salesTax;
double surCharge;
double total;
Scanner stdin = new Scanner(System.in);
//INPUT: number of seats sold
System.out.print ("Enter the number of Premium Seats Sold: ");
premiumSeats = stdin.nextInt();
System.out.print ("Enter the number of Standard Seats Sold: ");
standardSeats = stdin.nextInt();
System.out.print ("Enter the number of Economy Seats Sold: ");
economySeats = stdin.nextInt();
//PROCESS: i calculate the total and add the percent of tax based on the seats added
subTotal = premiumSeats * PREMIUM_PRICE + standardSeats * STANDARD_PRICE + economySeats * ECONOMY_PRICE;
salesTax = TAX_RATE * subTotal;
total = subTotal + salesTax + SURCHARGE;
//OUTPUT:
System.out.println();
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + salesTax);
System.out.println("surCharge: " + SURCHARGE);
System.out.println("Total: " + total);
}
}
put a while loop around each variable input and keep looping until the user gets it right. I didn't check if this compiles though.
while (true) {
try {
System.out.print ("Enter the number of Premium Seats Sold: ");
premiumSeats = stdin.nextInt();
if (premiumSeats >= 0){
break;
} else {
System.out.print ("Please Enter a positive integer.\n");
}
}
catch (Exception e){
System.out.print ("Please Enter a number.\n");
}
}
I have the following simple sales program and am having trouble creating a restart loop around the program. My primary issue is converting the boolean from a string to a boolean type, I am getting an error in Eclipse that says, "The method parseBoolean(String) is undefined for the type Boolean".
However, I have defined a boolean variable at the top, boolean tryAgain = false;
and for some reason I cannot set the user input scanner to take the True or False value without an error. The error is occurring with the last line when I try to cast the nextLine from the user to boolean.
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
The reason it gives you trouble is that when the user enters a double then hits enter, two things have just been entered - the double and a "newline" which is \n.
The method you are calling, "nextDouble()", only reads in the double, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you have to call nextLine() before your code would work.
Add this line before last line .
userInput.nextLine();
Well, I couldn't get it to work with a boolean for some reason, so I changed to a do while loop. Here is the final code. Also I did use the tip for clearing out the nextLine().
import java.util.Scanner;
public class Sales2 {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user inputjea
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
String answer; //Define var type of String for do while loop to restart program
do { //Do this loop while string == (last line of code while loop)
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (yes or no)"); //Prompt user for restart
userInput.nextLine(); //Clear scanner
answer = userInput.nextLine();
}
while (answer.equalsIgnoreCase("Yes")); //Connected to do while loop
//
}
}
Scanner supports nextBoolean(). Just use it:
tryAgain = userInput.nextBoolean()
Why do I keep getting the error
symbol not found
for hamburger, cheeseburger, etc.? I also am getting an error for the * sign. I used a template to create this program. I don't understand why it is not compiling.
import java.util.Scanner;
import java.text.NumberFormat;
public class Assignment2
{
public static void main (String[] args)
{
final (double) HAMBURGER_COST = 2.75;
final (double) CHEESBURGER_COST = 3.25;
final (double) FRENCHFRIES_COST = 2.50;
final (double) BEVERAGE_COST = 1.50;
String hamburger, cheeseburger, fries, beverages;
Scanner in = new Scanner(System.in);//allows user input
System.out.println("Welcome to the In-N-Out Burger menu:");
System.out.println("______________________________________");
System.out.println("Hamburger $2.75");
System.out.println("Cheeseburger $3.25");
System.out.println("French Fries $2.50");
System.out.println("Shake & Beverage $1.50");
System.out.print("How many hamburger(s) would you like to buy?");
hamburgers = scan.nextInt();
System.out.print("How many cheeseburger(s) would you like to buy?");
cheeseburgers = scan.nextInt();
System.out.print("How many French fries would you like to buy?");
fries = scan.nextInt();
System.out.print("How many drinks would you like to buy?");
beverages = scan.nextInt();
double hamburgerCost = (double)HAMBURGER_COST * hamburger;
double cheesebugerCost = (double)CHEESBURGER_COST * cheeseburger;
double frenchfriesCost = (double)FRENCHFRIES_COST * fries;
double beverageCost = (double)BEVERAGE_COST * beverages;
double orderCost = (double)hamburgerCost + (double)cheesebugerCost +
(double)frenchfriesCost + (double)beverageCost;
int numberItems = Hamburgers + Cheesburgers + Fries + Beverages;
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
System.out.println("Hamburger Cost : " + fmt1.format(hamburgerCost));
System.out.println("Cheeseburger Cost : " + fmt1.format(cheesebugerCost));
System.out.println("French Fries Cost : " + fmt1.format(frenchfriesCost));
System.out.println("Order Cost : " + fmt1.format(beverageCost));
System.out.println("Shake & Beverage Cost : " + fmt1.format(beverageCost));
System.out.println("Total number of items ordered : " + numberItems);
}
}
import java.util.*;
public class Averages{ //name class as public
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4= 0;
System.out.println("What class are you calculating for?");
Course = Scan.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = Scan.nextLine();
System.out.println("What's your application mark for this course?");
applicationmark = Scan.nextLine();
System.out.println("What's your thinking mark for this course?");
thinkingmark = Scan.nextLine();
System.out.println("What's your communication mark for this course?");
communicationmark = Scan.nextLine();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark)/4);
average = Scan.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = Scan.next();
if(answer.equals ("yes")){
System.out.println("What is your final exam mark?");
finalexam = scan.nextInt();
average2 = (((average * 70) + finalexam * 30) /100);
System.out.println("Your final average in this course is" + average2);
}
else{
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = Scan.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = Scan.nextLine();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = Scan.nextLine();
System.out.println("What is the weighting for communication?");
communicationweight = Scan.nextLine();
System.out.println("What is your communication mark for the test/assignment?");
maxC = Scan.nextLine();
System.out.println("What is the weighting for application?");
applicationweight = Scan.nextLine();
System.out.println("What is your application mark for the test/assignment?");
maxA = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
thinkingweight = Scan.nextLine();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = Scan.nextLine();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = Scan.nextInt;
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for(int i=0; i<length; i++){
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt[];
}
}
}
Here is my code. The error is near the bottom of the page. Thanks ahead of time!
Please hep me fix this as I do not know what to do
It is my only error left to compile.
Thanks and greatly appreciated!
Edit: Formatted to show code in one snippet.
You are missing () in your call to nextInt() at
weightaverage = Scan.nextInt;
change it to something like
weightaverage = Scan.nextInt();
and
firstArray[i] = scan.nextInt[];
should be
firstArray[i] = scan.nextInt();
And, you aren't consistent with your Scanner name.
Scanner sc = new Scanner(System.in);
needs to be
Scanner Scan = new Scanner(System.in);
if you're going to call Scan.nextInt(). Also, you are calling nextLine() (which returns a String) and assigning the result to int variables.
Here's the code corrected with suggestions made by Elliott Frisch.
To reiterate:
You declared Scanner with the variable name sc, but used Scan.nextLine() in the remainder of the code. The correction is sc.nextLine().
sc.nextLine() cannot be converted to String. It returns an integer so for example, int knowledgemark = sc.nextInt(); is correct.
Some code was using sc.nextInt; or sc.nextInt[]; which should be corrected to sc.nextInt();.
import java.util.*;
public class Averages { //name class as public
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4 = 0;
System.out.println("What class are you calculating for?");
Course = sc.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = sc.nextInt();
System.out.println("What's your application mark for this course?");
applicationmark = sc.nextInt();
System.out.println("What's your thinking mark for this course?");
thinkingmark = sc.nextInt();
System.out.println("What's your communication mark for this course?");
communicationmark = sc.nextInt();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark) / 4);
average = sc.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = sc.next();
if (answer.equals("yes")) {
System.out.println("What is your final exam mark?");
finalexam = sc.nextInt();
average2 = (((average * 70) + finalexam * 30) / 100);
System.out.println("Your final average in this course is" + average2);
} else {
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = sc.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = sc.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = sc.nextInt();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = sc.nextInt();
System.out.println("What is the weighting for communication?");
communicationweight = sc.nextInt();
System.out.println("What is your communication mark for the test/assignment?");
maxC = sc.nextInt();
System.out.println("What is the weighting for application?");
applicationweight = sc.nextInt();
System.out.println("What is your application mark for the test/assignment?");
maxA = sc.nextInt();
System.out.println("What is the weighting for knowledge?");
thinkingweight = sc.nextInt();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = sc.nextInt();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = sc.nextInt();
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for (int i = 0; i < length; i++) {
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt();
}
}
}
I'm trying to create a simple program that asks the user to input three items, their quantities, and prices. The program must allow the item names to have spaces. Here is my code that I have written so far.
import java.util.Scanner;
public class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = kb.nextInt();
System.out.print("\nPlease enter in the price of your item");
double price2 = kb.nextDouble();
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price3 = kb.nextDouble();
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}
My problem is that when I'm using String item = kb.nextLine(); here's an example of this process when entering the items
Please enter in your first item
soda
Please enter the quantity for this item
10
Please enter the price for this item
15
Please enter in your second item
Please enter the quantity for this item
At this point the first item is fine, but then it comes to the second item and it automatically inputs the second item line and moves straight onto the quantity, I don't understand how to fix this problem and I need to use nextLine(); so the item names can have spaces. Please help.
Try this code
import java.util.Scanner;
class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = Integer.parseInt(kb.nextLine());
System.out.print("\nPlease enter in the price of your item");
double price2 =Double.parseDouble( kb.nextLine());
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price3 = Double.parseDouble(kb.nextLine());
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}
Because you are using System.in, nothing is sent to the scanner until you've hit "enter". Meaning if you type "15" without hitting "enter", the kb.nextDouble(); call blocks. When you hit "enter" then kb.nextDouble(); reads "15", but there's still a newline in the scanner's buffer. That means this part of the code:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
Instantly reads the newline that was in the buffer from you typing "15" then hitting "enter". So it won't attempt to read an item name.
You can either replace all of your item name scanning from:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
to:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.next();
Or read the newline and parse the double when you scan for the price:
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
kb.nextDouble();
I need to check, but it looks likely that nextDouble leaves the newline intact which then is inputed by the consequent `nextLine.
You can solve this problem in two different ways:
Replace .nextLine() with .next() in your code. (But doing this will not allow you to have spaces in the string.
When you read a primitive and then you read a text, add another .nextLine(); after it.
Using the second method in your case you'll have:
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
String item2 = kb.nextLine(); // -------------> Added this line also here
//process for item two
System.out.println("\nPlease enter in your second item");
item2 = kb.nextLine();
Which will fix the first problem you have. Make the same for all other places, and your program will run as it supposed to.
Either Use different Scanner Objects for getting String and Numbers. This solves your problem.