I have to create a virtual coffee shop where the user enters their order number, how many of that order they want, calculate the subtotal and the discount, etc. The whole point of this is that the process's divided into various methods. Most of the methods are pretty simple, but I'm having trouble with the computeSubTotal method. I have to initialize subtotal in the main method to make this work, but when the subtotal's calculated in computeSubTotal, it always ends up being zero. Sorry if this seems stupid, but I have no idea what I'm doing wrong, help?
import java.util.Scanner;
public class CoffeeShopWithMethods
{
public static void main(String[] args)
{
Scanner user_input = new Scanner (System.in);
String user_name;
System.out.print("\nPlease enter your name: ");
user_name = user_input.next();
System.out.println("\nWelcome to the Java Byte Code Coffee Shop, " + user_name + "!");
int orderNumber = 0;
int orderQuan = 0;
double subTotal = 0.0;
//Beginning of calls to methods
displayMenu();
getItemNumber(orderNumber);
getQuantity(orderQuan);
computeSubTotal(orderNumber, orderQuan, subTotal);
discountCheck(subTotal);
}
public static void displayMenu()
{
System.out.println("\nHere is our menu: \n" + "\n 1. Coffee $1.50" + "\n 2. Latte $3.50" + "\n 3. Cappuccino $3.25" + "\n 4. Espresso $2.00");
}
public static int getItemNumber(int orderNumber) //prompts user for item number (1 for coffee, 2 for latte, etc...)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the item number: ");
orderNumber = user_input.nextInt();
final double Coffee = 1.50;
final double Latte = 3.50;
final double Cappuccino = 3.25;
final double Espresso = 2.00;
double Cost = 0;
if (orderNumber == 1)
Cost = Coffee;
if (orderNumber == 2)
Cost = Latte;
if (orderNumber == 3)
Cost = Cappuccino;
if (orderNumber == 4)
Cost = Espresso;
return orderNumber;
}
public static int getQuantity(int orderQuan)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the quantity: ");
orderQuan = user_input.nextInt();
return orderQuan;
}
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
public static boolean discountCheck(double subTotal) //takes subtotal and returns true if user earned a discount (over $10)
{
if (subTotal >= 10.00)
return true;
else
return false;
}
}
Your methods getItemNumber, getQuantity, computeSubTotal and discountCheck all return a value, but you are not storing that return value in your main method.
In addition to that, your getItemNumber() method is only storing the cost locally, which is then discarded when the method is finished - the cost should be returned (and the method probably renamed).
You probably should have something like this:
//Beginning of calls to methods
displayMenu();
double itemCost = getItemCost(); // was getItemNumber()
orderQuan = getQuantity(orderQuan);
subTotal = computeSubTotal(itemCost, orderQuan);
boolean shouldDiscount = discountCheck(subTotal);
Of course, to use an object-oriented approach, the variables should be members of your class, then you wouldn't need to pass or return values - they would be accessible to all methods in the class.
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
In your computeSubTotal method, you do
subTotal = (orderNumber * orderQuan);
This is not going to intiailize the variable in the main method; you are re-initializing the parameter variable.
In your main method, you should be doing
subTotal = computeSubTotal(orderNum, orderQuan);
instead of calling the method without using the return value. You might have noticed that I didn't pass subTotal to the method. This is not needed. You can instead re-declare the variable inside the method:
public static double computeSubTotal(int orderNumber, int orderQuan)
{
double subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
This applies to the other variables aswell. Java is pass-by-value, so if you pass a value to a method, a new reference is created for the method (when you do int varName in your method's parameters when you declare the method)
Related
I can't figure out how to return the value of finalCost to the main method and have it printed.
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
Specifically, I can't find how to use the returned value in the "println" line.
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
You call calcMonthlyCharge(downloadLimit),but don't store the returnvalue.
When you call System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
It is unknown what finalcost is, this is a variable which only exist in the scope of calcMonthlyCharge
Either store the returnvalue of calcMonthlyCharge(downloadLimit) and reuse the value to print, or use calcMonthlyCharge(downloadLimit) in your println with downloadLimit as parameter to get a new returnvalue.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
Here is my current program where it asks the user to input the item they're buying and the original price. The program will take a random percent off (between 5-75) and then give the user the new total price including a .07 tax added. The code is working great just that I'm not sure how to get the price amount to round to $0.00 and not have trailing numbers which ends up affecting the coins/dollars that the cash register would give in change. Any ideas? Thanks!
import java.util.Scanner;
import java.lang.Math;
import java.math.*;
import java.util.Random;
//declaring variables for methods
class Main
{
Scanner scan = new Scanner(System.in);
//random variable for while loop
int k=1;
//other variables
String name;
double taxRate = 0.07;
int dollars, quarters, dimes, nickels, cent, discountPercentage;
double discount, salePrice, tax, totalPrice, money, change, originalPrice, cents;
//method to run entire program
public void runProgram()
{
//make sure to create program including a while loop
while (k<2)
{
//here it explains the calculations and gets the user input of the item and original price of it
System.out.println("As part of a store promotion, each customer is given a random percent off");
System.out.println("Please enter the name of the item you plan to purchase: ");
name = scan.nextLine();
System.out.println("Enter the original price of that item: ");
originalPrice = scan.nextDouble();
scan.nextLine();
//here is where the user input is being calculated
discountPercentage = getDiscount();
discount = calculateDiscount(originalPrice, discountPercentage);
salePrice = calculateSalePrice(originalPrice, discount);
tax = calculateTax(salePrice);
totalPrice = calculateTotalPrice(salePrice, tax);
//print to user all the new calculations of item price
System.out.println("The original price of the item is: " + originalPrice);
System.out.println("The discount percent on the item is: " + discountPercentage + "%");
System.out.println("The new sale price of the item is: " + salePrice);
System.out.println("The tax of the item is: " + tax);
System.out.println("Now, the new total price of the item including the discount and tax is: " + totalPrice);
//this part will figure out how much money the user is giving the cashier and how much change needs to be given
System.out.println("How much money are you giving to the cashier?");
money = scan.nextDouble();
scan.nextLine();
change = solveChange(money, totalPrice);
System.out.println("The change you will be given back is: " + change);
convertChange(change);
System.out.println("\n");
}
}
//method for getting random discount for the item
public int getDiscount()
{
//discount can only be in multiples in 5 ranging from 5-75, and all the variables for this method
int multiple = 5;
int discountStart = 5;
int discountEnd = 75;
int calculateDiscountStart;
int calculateDiscountEnd;
calculateDiscountStart = discountStart / multiple;
calculateDiscountEnd = discountEnd / multiple;
//random generator for the discount
discountPercentage = new Random().nextInt(1 + calculateDiscountEnd - calculateDiscountStart) + calculateDiscountStart;
return discountPercentage * multiple;
}
//method for calculating the discount percent that is applied to original price of item
public double calculateDiscount(double originalPrice, int discountPercentage)
{
discount = originalPrice * discountPercentage / 100;
return discount;
}
//method to calculate the price with the discount applied to the item
public double calculateSalePrice(double originalPrice, double discount)
{
salePrice = originalPrice - discount;
return salePrice;
}
//method to calculate the tax
public double calculateTax(double salePrice)
{
tax = salePrice * taxRate;
return tax;
}
//method that will calculate the overall price including tax (adding previous methods together)
public double calculateTotalPrice(double salePrice, double tax)
{
totalPrice = salePrice + tax;
return totalPrice;
}
//method that takes user input of how much money giving and calculating how much change they need
public double solveChange(double money, double totalPrice)
{
change = money - totalPrice;
//int dollars = change/1;
return change;
}
//method to convert the change the user needs to dollars, quarters, etc
public double convertChange(double change)
{
cents = change*100;
dollars = (int)cents/100;
quarters = (int)(cents % 100)/25;
dimes = (int)((cents%100)%25)/10;
nickels = (int)(((cents%100)%25)%10)/5;
cent = (int)((((cents%100)%25)%10)%5);
//printing out the amount of change to the user
System.out.println("Amount of change in Dollars is: " + dollars);
System.out.println("Amount of change in Quarters is: " + quarters);
System.out.println("Amount of change in Nickels is: " + nickels);
System.out.println("Amount of change in Dimes is: " + dimes);
System.out.println("Amount of change in Cents is: " + cent);
return change;
}
//main method using static
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
What you usually do in real world programs that involve money: you use an int that is the total amount of pennies. So $ 1.99 = 199 int.
The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);
I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}