Creating a running total for one of my methods - java

Hello i am having trouble creating a running total of one of my methods.
public double calcProduct()
{
productTotal = price * qty * shipCost;
return productTotal;
}
the method i have listed above is supposed to calculate the total of 4 instances i have created but for some reason it is adding up the same number of "562" despite shipping cost and all the products being priced different. I also need a grand total of the 4 instances in one set price. i also have a static double called productTotal uninitialized.
Edit: Here is a copy of my code for the "SalesOrder method and main method:
Main:
public class SalesOrderDemo
// and initialize it to 0
double grandTotal = 0;
// Print out a heading line as follows:
// "Sales Orders"
System.out.println("Sales Orders");
// "------------"
System.out.println ("------------");
// Orders to place ...
System.out.println ("Orders to place...");
// Use the overloaded constructor to create
// the Following instances of Sales Order:
//
// Instance #1 -- instance name: samsungTV
// "Samsung 65 inch Television" - qty 1 - price $199.99
// To be shipped normal
SalesOrder Instance1 = new SalesOrder();
Instance1.setProductName ("Samsung 65 inch Television");
Instance1.setQty (1);
Instance1.setPrice(1599.99);
Instance1.calcShipping("normal");
// Instance #2 -- instance name: smartLights
// "Hue Smart Lights" - qty 6 - price $49.95
// To be shipped same day
SalesOrder Instance2 = new SalesOrder();
Instance2.setProductName ("Hue Smart Lights");
Instance2.setQty (6);
Instance2.setPrice(49.95);
Instance2.calcShipping("sameDay");
// Instance #3 -- instance name: bathTowels
// "Bathrool Towels" - qty 8 - price $19.45
// To be shipped 2nd day
SalesOrder Instance3 = new SalesOrder();
Instance3.setProductName ("Bathroom Towels");
Instance3.setPrice(19.45);
Instance3.setQty(8);
Instance3.calcShipping("2-day");
// Instance #1 -- instance name: samsungTV
// "Dinner Plates" - qty 15 - price $2.50
// To be shipped same day
SalesOrder Instance4 = new SalesOrder();
Instance4.setProductName("Dinner Plates");
Instance4.setQty(15);
Instance4.setPrice(2.50);
Instance4.calcShipping("sameDay");
// Execute the mutator method "calcShipping" to add the
// appropriate shipping fee to the cost of the product
// The method will pass the shipping type string parameter:
// A character to store the type of shipping method
// "normal" for no additional shipping charge
// "2-day" for adding $2 to the shipping fee for 2 day delivery
// "same" for adding $10 to the shipping fee for same day delivery
// Execute the method for each of the instances you created above
// Execute the get method "calcProdcut" to
// 1. Calculate the total amount for each product,
// 2. Print the products information on each line
// 3. Return to total amount value to be accumulated into "grandTotal"
// Execute the method for each of the instances you created above
Instance1.calcProduct();
Instance2.calcProduct();
Instance3.calcProduct();
Instance4.calcProduct();
grandTotal = Instance1.calcProduct() + Instance2.calcProduct()
+ Instance3.calcProduct() + Instance4.calcProduct();
// Print all total of all of the orders as shown on the example
// Format to 2 decimal places
// Don't forget to print a blank line
Instance1.printProduct();
System.out.println("");
Instance2.printProduct();
System.out.println("");
Instance3.printProduct();
System.out.println("");
Instance4.printProduct();
System.out.println(" ");
System.out.println("The total of the orders are: " + grandTotal);
}
}

It seems like you're having a bit of a misunderstanding of what "instance methods" allow you to do.
So, you're calling calcProduct twice, but no other SalesOrder instance knows about the values of the others, and that's by design. No matter how many times you run that method, result should be the same.
That being said, this is all you need. The shipping is probably not considered part of the product price. And it should be added, maybe, rather than multiplied (assuming all products of unlimited quantity are shipped at once, for a flat rate)
public double calcProduct() {
return price * qty;
}
The correct way to calculate the total would be to sum each one, like you're already doing. Getter methods should not have side effects and alter results of other instances.
Note, it would be much simpler, if you used a loop over an arraylist
List<SalesOrder> orders = new ArrayList<>();
// add orders
double grandTotal = 0;
for (SalesOrder so : orders) grandTotal += (so calcProduct() + so.calcShipping());

Related

Jgrasp java 26 error: class, interface, or enum expected

I'm working on a project for my class and every time I try to compile I get the following error in jGrasp:
Lab 1.java:26: error: class, interface, or enum expected
Module main()
^
1 error
I have tried looking for the error in my code but can't find it if anyone sees what is wrong that I'm overlooking that would very helpful and I would appreciate any corrections that would get rid of that error. The code is below so you can get a thorough look at it.
/*Problem: Rent
Analyze, design and code the following application:
It allows a user to enter the rent of a home and
calculate the first month payment. The first month
payment includes a security deposit (equal to the 2 months rent)
and the first month's rent.Display the following:
each month’s rent, amount of security deposit and the final payment.
Input
User: 1. Rent amount
Given: N/A
Processing: 1. Calculate security deposit = 1 month rent * 2
2. Calculate total first month rent =
1 month rent + security deposit
Output: 1. Price for 1 month of rent
2. Price of security deposit
3. Total for first months' rent
*/
//Design
Module main()
//Declarations
Declare Real oneMonthRent = 0.0//One month rent entered by user
Declare Real securityDeposit = 0.0//2 months worth of rent
Declare Real firstMonthRent = 0.0//Security deposit + 1 month rent
//Input
Set oneMonthRent = Call getRent()//user entered
//Processing
Set securityDeposit = Call calcDeposit(oneMonthRent)//oneMonthRent + oneMonthRent
Set firstMonthRent = Call calcFirstMonthRent(oneMonthRent, securityDeposit)//oneMonthRent + securityDeposit
//Output
Call showRentAnalysis(oneMonthRent, securityDeposit, firstMonthRent)//Displays oneMonthRent, Deposit, and total first month
End Module
//Gets monthly rent cost from user
Function Real getRent()
Declare Real nRent = 0.0//local variable
Display "Enter monthly rent "
Input nRent
Return nRent
End Function
//Calculates the Security deposit
Function Real calcDeposit(Real noneMonthRent)
Declare Real ndeposit = 0.0//local variable
Set ndeposit = noneMonthRent + noneMonthRent
Return ndeposit
End Function
//Calculates total first month rent
Function Real calcFirstMonthRent(Real noneMonthRent,Real nsecurityDeposit)
Declare Real nfirstMonthRent = 0.0//local variable
Set nfirstMonthRent = noneMonthRent + nsecurityDeposit
Return nfirstMonthRent
End Function
//Displays 1 month of rent, security deposit, and final for first month
Module showRentAnalysis(Real noneMonthRent,Real nsecurityDeposit,Real nfirstMonthRent)
Display "One month worth of rent cost ", noneMonthRent
Display "Security deposit cost ", nsecurityDeposit
Display "Total for first month of rent is ", nfirstMonthRent
End Module
public class Main {
public static void main(String[] args) {
double rent = 500.50;
double securityDeposit = rent*2;
double firstMonth = rent+securityDeposit;
System.out.println(firstMonth);
}
}

How do I create a method to calculate a commission fee in Java

I am trying to create a method in Java where a band has a commissioning fee based on the number of artists it has. So it will be 10 pounds for each artist.On the program, when you create the band, you input the artists in the band. The commission fee is then based on the number of artists ( £40 for each artist).
What I currently have is:
private void setCommission()
{
commission = artists+40;
}
Can someone advise on how I can get my method to function correctly or if theres anything else I should add to my current version.
private void setCommission() {
commission = (artists * 40);
}
Your math is messed up. It should be artists * 40 Or, if artists is a list of some sort than you need to multiply its length by 40.

How to solve this program?

I found this Java exercise :
Create a class Sales that has TotalSales (double) , Commission (double),
Commissi onRate (double), and NoOfItems (integer).
write a java application that asks the user to enter the Total Sales and the number of items then calculates the commission and prints it out.
The commission rate should be as following:
Condition :
Less than 500, commissionRate is 0
Greater than or equal 500 or Number of Items >= 5, commission rate is 5%.
Grater than or equal 1000 or Number of items >=10, commission rate is 10%
..
I wrote this code:
Main Class :
import java.util.Scanner;
public class testSales {
public static void main(String[] args) {
Sales s1 = new Sales();
Scanner get = new Scanner(System.in);
System.out.println("Enter total Sales");
s1.totalSale = get.nextDouble();
System.out.println("Enter number of Items");
s1.NoOfItems = get.nextInt();
if(s1.totalSale < 500){
s1.commission = s1.commissionRate = 0;
}
else if(s1.totalSale >= 500 && s1.totalSale <= 999 || s1.NoOfItems >= 5 && s1.NoOfItems <=9){
s1.commission = s1.commissionRate = s1.totalSale * 5 / 100;
}else if(s1.totalSale >= 1000 || s1.NoOfItems >=10) {
s1.commission = s1.commissionRate = s1.totalSale *10/100;
}
System.out.println(s1.commission);
}
}
One problem in your code is the case where NoOfItems > 5 but totalSale < 500. For this case, the commission will incorrectly be set to 0 because the first if statement eats it.
Please try to be more specific with your question. "this doesn't work and I don't know why" is not easy to help with.
Aside from the point brought up by HedonicHedgehog, there are a few other things to consider:
The sales class only has two global variables, which corresponds to the information entered by the user. The other two fields, commission and commissionRate, are calculated values. Therefore, there is no need to create variables for them. Just add to the sales class accessor methods (getters) that return these values. For example, below is my getCommission() method:
public double getCommission()
{
return totalSales * getCommissionRate();
}
Of course, you can see this method is dependent upon the getCommissionRate() method. Because there is a gap on your requirements with total items, I am ignoring it for now:
public double getCommissionRate()
{
if (totalSales < 500)
return 0;
if(totalSales < 1000)
return .05;
else
return 0.1;
}
Alternatively, you could create a LOCAL commission variable, and set the value before returning it. It is a good programming practice to limit the scope of your variables. In this case, there is not a good reason to have a global commission or commissionRate variables.
Lastly, your test class is simplified because all you need to do is to prompt the user for the two needed fields, and it simply spits out the output because the Sales class provides the calculation needed to figure out the rest:
public static void main(String[] args)
{
Sales s1 = new Sales();
Scanner input = new Scanner(System.in);
System.out.print("Enter total Sales");
s1.setTotalSales(input.nextDouble());
System.out.print("Enter number of Items: ");
s1.setNumOfItems(input.nextInt());
System.out.printf("$%.2f", s1.getCommission());
input.close();
}
I used the printf() method to format the output string. The following is a sample run:
Enter total Sales: 503.45
Enter number of Items: 5
$25.17
Enter total Sales: 1003.67
Enter number of Items: 19
$100.37
Enter total Sales: 45.00
Enter number of Items: 19
$0.00
Remember that this example ignores the number of items because of the reasons already mentioned. Once you figure out what needs to be done to cover of the gap in the requirements, you can modify this code to do the rest. Also remember that your Sales class only requires two fields: totalSales and numOfItems. The other to components (commission, and commissionRate) are calculated; therefore, no global variable or setter methods needed. Just the two getter methods I provided.

Cannot use arrays or foreach loops to iterate over list of data and print out only certain values

The Prompt:
A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.
b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more.
Here is an example of a good design in operation:
High-priced, Best-selling Candy
Fudge $12.50 4500 lbs
Vanilla Creme $13.75 2200 lbs.
Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200
Item that sold most pounds: Jawbreakers
but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this?
start
// Declarations
num QUIT = "Y";
final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n";
final String HSPS = candyName + " " + candyPrice + " " + candySold + " ";
final String MOSTSOLD = "Item that sold the most pounds is "
while <> QUIT;
enterCandy();
printHighPriceBestSelling();
printSoldMostPounds();
endwhile;
stop
entercandy()
String candyName = "poop";
double candyPrice = 0.0;
double candyWeight = 0.0;
int candySold = 0;
output "Please enter name of candy.";
input candyName;
output "Please enter candy price.";
input candyPrice;
output "Please enter pounds sold.";
input candySold;
printHighPriceBestSelling()
if(candySold > 2000 && candyPrice > 10)
{
output HEADING;
output HSPS;
}
else
{
output "There were/are no best selling, high priced candy!"
}
printSoldMostPounds();
//There is no basis for comparison.
There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way?
output "MOSTSOLD ";
I'm assuming that, besides arrays, you're teacher isn't allowing you to use any standard Collection objects.
You could always just build your own LinkedList of entered candy orders--it's ugly, but it would work. A single "link" in the chain would look like this
public class CandyOrderLink {
private String candyName;
private Double candyPrice;
private Double orderAmount;
private CandyOrderLink nextOrderLink;
public CandyOrderLink(String candyName, Double candyPrice, Double orderAmount) {
this.candyName = candyName;
this.candyPrice = candyPrice;
this.orderAmount = orderAmount;
}
public CandyOrderLink getNextLink() {
return nextOrder;
}
public void setNextLink(CandyOrderLink nextOrderLink) {
this.nextOrderLink= nextOrderLink;
}
public String getCandyName() {
return candyName;
}
public Double getCandyPrice() {
return candyPrice;
}
public Double getOrderAmount() {
return orderAmount;
}
}
Not sure if I'm quite grasping the point of the assignment, but using a list data-structure to keep track of all orders will work. Just build a link for each entry (candyName, price, amount) and set that link as the next link of the previous one. At the end of input, iterate through the list by repeatedly calling getNextLink() on each link and printing information (if appropriate). Here is Wikipedia's article on linked lists: http://en.wikipedia.org/wiki/Linked_list
From the problem's description, I see no need to store the data entered so that it can be sorted. Both a and b state simple conditions for displaying a candy: greater than 2,000 pounds and at least $10/lb. You can print each entry immediately after it is entered.
However, your example output implies that you must pick the single best-selling candy which contradicts the description. Which is correct?

Java method passing/ordered logic inquiry

Let me first make it clear that this is for an assignment. I'm very new to programming so all guidance is greatly appreciated. The program I have to calculate is a parking fee charge for a $2.00 minimum for 3 hrs or less, .50 cents per additional hr, and charge is capped at $10/ per 24 hr period. Program must display most recent customer charge as well as running total. Constants must be initialized, Math.ceil must be used, and method calculateCharges must be used to solve each cust's charge. I get uber errors when I attempt to run this program, and you'll probably laugh when you see it, but where have I erred? I'm not looking for the answer to be handed to me, just looking for the logic behind how to get to the correctly written program. Please help!
package Parking;
import java.util.Scanner;
public class parking
{
private static final double THREE_HOURS = 2.00;
private static final double PER_HOUR_COST = .50;
private static final double WHOLE_DAY_COST = 10.00;
public static void main (String [] args)
{
double hoursParked = 0;
double cumulativeCharges = 0;
double storage1 = 0;
double storage2 = 0;
Scanner input = new Scanner(System.in);
System.out.print("\nThis program displays the charge for the most recent customer");
System.out.print(" as well as the running total of yesterday's receipts\n");
do
{ System.out.printf("Enter an number between 1-24 for hours parked in garage or -1 to quit:");
hoursParked = input.nextDouble ();
}
while((hoursParked > 0)&&(hoursParked <= 24)&&(hoursParked != -1));
if( hoursParked <= 3)
System.out.printf("Most recent customer's charge was: %.2f\n" , THREE_HOURS);
storage1 += THREE_HOURS;
if(hoursParked >= 18.01)
System.out.printf("Most recent customer's charge was:%.2f\n" , WHOLE_DAY_COST);
storage2 += WHOLE_DAY_COST;
double result = calculateCharges(hoursParked * PER_HOUR_COST);
System.out.printf("Most recent customer charge was:%.2f\n" , result);
cumulativeCharges = storage1 + storage2;
System.out.printf("Running total of yesterday's receipts is:%.2f\n" , cumulativeCharges);
} // end main
public static double calculateCharges (double hoursParked)
{
Math.ceil(hoursParked);
double total = hoursParked * PER_HOUR_COST;
return total;
} // end method calculateCharges
} // end class parking
In your while condition, the third condition is useless because if the value is positive, that necessarily means it is different than -1.
In your function you want to calculate the cost of parking time but you give as parameter a cost instead of a number of hours when you call your function. Is that normal? With that you will calculate the cost of the cost instead of the cost corresponding to a number of hours.
public static double calculateCharges (double hoursParked)
and
double result = calculateCharges(hoursParked * PER_HOUR_COST);
There's a couple things here.
Your while condition is checked at the end of the do loop, it is what allows you to break after reading hoursParked. Thus, the only way you are going to reach the code outside of the do loop (after the while), is if hoursParked is -1.
Secondly, when you do not have braces for your if conditions, you are only executing the first line after it, aka. the System.out.print's. Therefore, your first if condition will execute (printing the string), then storing 2.00 in storage1. Similarly, the second if condition will execute (printing the string), then storing 10.00 in storage2.
Because hoursParked is always -1, you are passing in (-1 * .5) to calculateCharges. You are not storing the result of Math.ceil() so it effectively does nothing. You are then returning (-.5 * .5) = -.25.
cumulativeCharges is just adding 2 + 10 in every case.
Suggestions - make sure you are encapsulating the code you want to execute inside the do loop, and only break after you have done your calculations on hoursParked.

Categories

Resources