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");
}
}
This is the part where I ask the user to input the following.
Enter the item name: Shirt
Original price of the item: 700
Marked-up Percentage: 20
Sales Tax Rate: 7
Output:
Item to be sold : Shirt
Original price of the item: 700.00
Price after mark-up: 840.00
Sales tax: 58.80
Final price of item: 898.80
so my question is how can I make that 20 and 7 input be read by the program as percentages.
import java.util.*;
import javax.swing.*;
public class lab3 {
public static void main(String[] args) {
JOptionPane jo=new JOptionPane();
String item=jo.showInputDialog("Item to be sold: ");
double Oprice=Double.parseDouble(
jo.showInputDialog("Original price of the item: "));
double mup=Double.parseDouble(
jo.showInputDialog("Marked-up percentage: "));
double str=Double.parseDouble(
jo.showInputDialog("Sales Tax Rate: "));
double pamu=(Oprice*mup)+Oprice;
double ST=pamu*str;
double result=pamu+ST;
String hold= "\n| Item to be sold \t: "+item+"\t |"
+"\n| Original price of the item \t: "+Oprice+"\t |"
+"\n| Price after mark-up \t: "+pamu+"\t |"
+"\n| Sales Tax \t: "+ST+"\t |"
+"\n| Final price of the item \t: "+result+"\t |";
jo.showMessageDialog(null, new JTextArea(hold));
}
}
That is my actual code. sorry if its messy. like I said still new to this
Let's use Scanner for reading from user:
Scanner sc = new Scanner(System.in);
double percentage = 0.01 * sc.nextInt();
will do the trick.
double pamu = (Oprice*(mup/100)) + Oprice; // enter code here
double ST = pamu*(str/100) ;
double result = pamu+ST ;
I think this should work.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name:");
String item;
keyboard.nextLine();
System.out.println("Original Price of item:");
double originalPrice;
keyboard.nextDouble();
System.out.println("Marked up percentage:");
double markedUpPercentage;
keyboard.nextDouble();
markedUpPercentage = markedUpPercentage/100; //this is what you want
System.out.println("Sales tax rate:");
double salesTaxRate;
keyboard.nextDouble();
salesTaxRate = salesTaxRate/100; //same thing here
//now output
System.out.println("Item to be sold: " + item);
System.out.println("Original price of the item: " + originalPrice);
System.out.println("Price after mark up: " + (originalPrice + originalPrice * markedUpPrice));
//similarly, do for sales tax
When I call this code in Terminal on my Mac it tells me "could not find or load main class" also it gives me a lot of errors on all of my code regarding printf.
I am new to Java so I assume this code is error ridden.
All I am really asking is how to fix it so it will run in terminal when I type "java itemprice" for it to not show an error.
Also I would like some help with the system.out.printf code.
import java.util.Scanner;
public class itempricecalc {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("What is your first name?");
String fname = scanner.nextLine();
String invf = fname.substring(0,2);
System.out.print("What is your last name?");
String lname = scanner.nextLine();
String invl = lname.substring(0,2);
System.out.println("Your name is: " +fname + lname);
System.out.println("What is your zipcode?");
int zipcode = scanner.nextInt();
invoice = (invf + invl + zipcode);
double salestax = 6.25;
double subtotal = 0;
System.out.println("What is item 1 called?")
String itemonename = scanner.nextLine():
System.out.println("Enter price of item 1");
double itemone = scanner.nextDouble();
System.out.println("How many of item 1 did you purchase?");
int itemoneamount = scanner.nextInt();
System.out.println("What is item 2 called?")
String itemtwoname = scanner.nextLine():
System.out.println("Enter price of item 2");
double itemtwo = scanner.nextDouble();
System.out.println("How many of item 2 did you purchase?");
int itemtwoamount = scanner.nextInt();
System.out.println("What is item 3 called?")
String itemthreename = scanner.nextLine():
System.out.println("Enter price of item 3");
double itemthree = scanner.nextDouble();
System.out.println("How many of item 3 did you purchase?");
int itemthreeamount = scanner.nextInt();
double itemonetp = itemoneamount * itemone;
double itemtwotp = itemtwoamount * itemtwo;
double totalprice = itemonetp + itemtwotp;
subtotal = subtotal + totalprice;
double taxtotal = subtotal * salestax;
System.out.print("Your name is: " + fname + " " + lname)
System.out.printf(“Invoice: %.2f”, invoice);
System.out.printf(“Total price of item one is + %.2f”, itemonetp);
System.out.printf(“Total price of item two is + %.2f”, itemtwotp);
System.out.printf(“Total price of your purchase is + %.2f”, totalprice);
System.out.printf(“Your total with tax comes to + %.2f”, taxtotal);
System.out.printf(“You purchased + %.2f + amount of item one”, itemoneamount);
System.out.printf(“You purchased + %.2f + amount of item two”, itemtwoamount);
}
}
I've written the following program and am having an issue when trying to call the "calculateTotalPrice" method back into the main method to compute the final pricing. I'm not sure if it is an error with my method or my call. Main works as desired without the call to the "calculateTotalPrice" method. Can anyone give any suggestions as to how I should rearrange the secondary method or call statement? Thanks
public class GrapefruitOrderingArray {
//Declare Constants
public static final int SIZE = 100;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Declare Variables
Scanner input = new Scanner (System.in); //Input new scanner system
String CustomerName; //Declare customer's name as a string
int nNumber = 0; //Declare integer variable for nNumber
int nProducts = 0; //Declare integer variable for nproducts
int nTotal; //Declare integer variable for ntotal
double[] nFinalPrice = new double [SIZE];
int [] itemPrices = {49,299,329,399,199,1299,1199,999,599}; //Declare integer variable array
int nCount = 0;
//Declare Constants
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Prompt user to enter name
System.out.println("Please enter your name: ");
//Enter user name
CustomerName = input.nextLine();
//Print Blank Line
System.out.println("");
//Begin Product Listing Declarations with respect to array above
System.out.println("GRAPEFRUIT PRODUCT:");
System.out.println("1. gPod shuffle $" + itemPrices[0]);
System.out.println("2. gPod Touch $" + itemPrices[1]);
System.out.println("3. gPad Mini $" + itemPrices[2]);
System.out.println("4. gPad 2 $" + itemPrices[3]);
System.out.println("5. gPhone $" + itemPrices[4]);
System.out.println("6. gMac $" + itemPrices[5]);
System.out.println("7. MacNovel Pro $" + itemPrices[6]);
System.out.println("8. MacNovel Air $" + itemPrices[7]);
System.out.println("9. MiniMac $" + itemPrices[8]);
System.out.println("10. Complete my order");
// Keep reading until the input is 10
System.out.println("\nPlease select an item from the menu above: ");
//Begin while-loop statement
while (nNumber != SENTINEL) {
//Read number entered by the user
nNumber = input.nextInt();
if (nNumber == SENTINEL) {
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
break;
}
//Call final price calculation
nFinalPrice = calculateTotalPrice(nNumber);
//If desired the user may select another or multiple products now
System.out.println("\nPlease select another item from the menu above: ");
}
//Print blank line to screen
System.out.println("");
//Total amount of product ordered
System.out.println("Total items ordered: " + nProducts );
//Total price of items ordered
System.out.println("Price of items ordered: $" + nTotal );
//Sales tax associated with the purchase
System.out.println("Sales tax: $" + SALES_TAX * nTotal );
//Total amount due by the customer to Grapefruit Co.
System.out.println("Total amount due: $" + (SALES_TAX * nTotal + nTotal));
}
} //End main method
/**
* This method calculates the total price of the products ordered
* #param itemPrice Individualized product prices
* #param nProduct Total price of items paid for
* #return nTotals Returns the number of the product associated with it's initialized price
*/
private static double[] calculateTotalPrice(int nNumber) {
//Calculate entered items
nTotal = nTotal + itemPrices [nNumber-1];
//Increment the total number of products entered
nProducts++;
return nNumber;
} //end method calculateTotalPriceOfItemsOrdered
} //end class calculateTotalPriceOfItemsOrdered
There are several problems here:
int nTotal =0; Happens after int nTotal is taken in as a parameter.
SIZE isn't declared anywhere.
More of a side note, but your comments are overly excessive.
This program returns the total price of the items selected by a customer. Hope it will help you.
import java.util.*;
public class CalTotalPrice {
static int totalPrice=0;
static int [] itemPrices = {49,299,329,399,199,1299,1199,999,599};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//declaring variables
String CustomerName;
int itemNumber = 0;
int noOfProducts = 0;
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Getting customer name
System.out.println("Please enter your name: ");
CustomerName = input.nextLine();
System.out.println("");
//Begin Product Listing Declarations with respect to array above
System.out.println("GRAPEFRUIT PRODUCT:");
System.out.println("1. gPod shuffle $" + itemPrices[0]);
System.out.println("2. gPod Touch $" + itemPrices[1]);
System.out.println("3. gPad Mini $" + itemPrices[2]);
System.out.println("4. gPad 2 $" + itemPrices[3]);
System.out.println("5. gPhone $" + itemPrices[4]);
System.out.println("6. gMac $" + itemPrices[5]);
System.out.println("7. MacNovel Pro $" + itemPrices[6]);
System.out.println("8. MacNovel Air $" + itemPrices[7]);
System.out.println("9. MiniMac $" + itemPrices[8]);
System.out.println("10. Complete my order");
System.out.print("\nPlease select an item from the menu above: ");
while (itemNumber != SENTINEL) {
itemNumber = input.nextInt();
if (itemNumber <= SENTINEL) {
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
break;
}
noOfProducts++; //increse number of products ordered
totalPrice= calculateTotalPrice(itemNumber);
System.out.print("\nPlease select another item from the menu above: ");
}
System.out.println("");
System.out.println("Total items ordered: " + noOfProducts);
System.out.println("Price of items ordered: $" +totalPrice);
System.out.println("Sales tax: $" + SALES_TAX *totalPrice);
System.out.println("Total amount due: $" + (SALES_TAX *totalPrice+totalPrice));
}
public static int calculateTotalPrice(int itemNumber) {
totalPrice=totalPrice+ itemPrices[itemNumber-1];
return totalPrice;
}
}
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.