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());
I am working on Spring+Hibernate based web application.
In this application I have to do calculation on 50000 records available into the database.
Current logic :-
Loop through 0 to 50000 (All 50000 records are independent to each other)
Select ith element
Do calculation on ith element (Drop CALCULATION_TEMP table if exist, create new table CALCULATION_TEMP and insert calculation in CALCULATION_TEMP table)
Do some calculation on step 3 table and get the result
Put step 4 result into Results table
Currently these all calculation taking around 38 hours to complete with single thread.
Now we want to run this system by multiple threads.
For testing purpose I have taken 50 records.
Using Single thread it is taking around 30 sec.
Using two threads :-
Half records performing by first thread and rest of the records by second thread.
Now I am using two TEMP tables for both threads. (TEMP1 and TEMP2)
It is taking 225 sec.
Rough Code :-
for (int i = 0; i < recordsSize; i++) {
final int j = i;
String recordId = list.get(i);
// Method call : Code for creating CALCULATION_TEMP table
// CALCULATION_TEMP table will contain dynamic number of column. It is depends on the record data (50 to 70 columns)
// return flag value
boolean flag = xyzMethod(....);
if (flag) {
// All calculation done in this method
// Around 600 - 700 rows will be created into CALCULATION_TEMP table on the basis of calculation logic
Object fileMapColumnData[] = /* Method call */;
// Insert result for one record into RESULT table for unique recordId (this result is calculated in CALCULATION_TEMP table)
insertIntoResultTable(....);
// Drop CALCULATION_TEMP table
} else {
LOGGER.error("Unable to calculate ... because of some wrong data");
loggerDTO.getCustomLogger().severe("Unable to calculate ... because of some wrong data");
}
if (i % 100 == 0) {
calculationDao.flushAndClear();
}
// Thread for showing process completion status in percentage
Thread t = new Thread() {
#Override
public void run() {
getPercentageDone((float) recordsSize, (float) (j + 1));
}
};
t.start();
}
Please suggest, How I can improve the performance.
Creating/Droping temporary tables take a lots of time by 50000 times. Can you do calculations without temporary table ? It can improve peformance.
There is no hard and fast rule for performance improvements. If you are having constraints and business decisions, we need to know the calculations and how the threads are managed, connections are managed and the number of loops involved etc. There are so many things to consider. Start with checking the pain point areas, the time taken for it and improve each method first.
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.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
For those people already read my last post, I do have a different solution for this. Please don't just walk away.
This is an assignment question from school (Sorry for the long story, I already tried shorten it)
I tend to order food based on how much money I have on me. I like to tip at least 15% regardless of service (I do enough evaluating performance in any given week already) and I hate the whole process of giving my money, waiting for the waitress to come back with the change the trying to find the correct change to make a proper tip. What I do is examine the menu for the combination of foods that best matches the money I have on me. When I say best matches, I mean closest to 15% without going under, and I only pick each food item once. As you can imagine it takes me a bit of time to compute all of this so I want you to make a method that I can use.
The method only has to work for the following menu:
Bandera Pizza Bread 6.49
Boston's Pizza Bread 5.35
Garlic Twist Bread 7.49
Single Order 5.35
Sun-Dried Tomato Bruschetta 6.99
Three Cheese Toast 6.35
Double Order wings 16.49
Starter Size wings 8.99
Cactus Nachos 10.29
Baked Ravioli Bites 8.49
Southwest Quesadilla 9.25
Create a method called selectFood that takes the amount of money I have as a parameter, outputs the selections on the screen and returns the percentage tip I will be leaving rounded to one decimal place. Don't worry if there is more food than two people can eat, I often go out with larger groups.
Some example output:
Best order for $10.00 is:Baked Ravioli Bites
The tip is 17.79%
Best order for $20.00 is:Sun-Dried Tomato Bruschetta, Cactus Nachos
The tip is 15.74%
Best order for $60.00 is:Bandera Pizza Bread, Boston's Pizza Bread, Three Cheese Toast, Double Order wings, Starter Size wings, Baked Ravioli Bites
The tip is 15.03%
Best order for $190.00 is:Bandera Pizza Bread, Boston's Pizza Bread, Garlic Twist Bread, Single Order, Sun-Dried Tomato Bruschetta, Three Cheese Toast, Double Order wings, Starter Size wings, Cactus Nachos, Baked Ravioli Bites, Southwest Quesadilla
The tip is 107.58%
My teacher has a restriction - we are not allowed to use an arraylist.
Here's my newest try:
import java.util.*;
class MethodAssign7{
public static void main(String[]args){
boolean[] took = {false,false,false,false,false,false,false,false,false,false,false};
double money = 70.0;
//System.out.println(selectFood(money/1.15,took));
selectFood(money,took);
System.out.println(closest/money*100+15);
}
static double closest = 10000.0;
static void selectFood(double money, boolean[] took){
String[] food = {"Bandera Pizza Bread","Boston's Pizza Bread","Garlic Twist Bread","Single Order","Sun-Dried Tomato Bruschetta","Three Cheese Toast","Double Order wings","Starter Size wings","Cactus Nachos","Baked Ravioli Bites","Southwest Quesadilla"};
double[] costs = {6.49,5.35,7.49,5.35,6.99,6.35,16.49,8.99,10.29,8.49,9.25};
if(money<5.35){
if(money<closest){
closest = money;
}
}
else{
for(double d: costs){
if(money-d*1.15>0){
//System.out.println(money-d);
selectFood(money-d*1.15,took);
}
}
}
}
/*static void printSelections(double money, boolean[] took){
String[] food = {"Bandera Pizza Bread","Boston's Pizza Bread","Garlic Twist Bread","Single Order","Sun-Dried Tomato Bruschetta","Three Cheese Toast","Double Order wings","Starter Size wings","Cactus Nachos","Baked Ravioli Bites","Southwest Quesadilla"};
double[] costs = {6.49,5.35,7.49,5.35,6.99,6.35,16.49,8.99,10.29,8.49,9.25};
if(money<5.35){
if(money==closest){
print the choices by using took
}
}
else{
for(int i=0;i<costs.length;i++){
if(money-costs[i]*1.15>0 && took[i]!=true){
took[i]=true;
//System.out.println(money-d);
selectFood(money-costs[i]*1.15,took);
}
}
}
}*/
}
I'm trying to solve the percentage part of the question first with dynamic programming, I can get the percentage answer with my program, but it takes too long for money input above 60. I tried to addin the boolean list "took" to indicate which ones are already picked but it did not work at all and got me confused :(
All the parts that's commented out are for the output of selections of food. And I know my selectFood method is only void right now and won't return value, but I think that's easier to fix. All I care right now is how do I get this percentage part working.
Thank you for your time reading my question, if you can help me I would appreciate it very much or if you don't get what I'm asking please leave a comment to tell me.
The simple version of this is that you start with an amount of money, x. At least a certain amount of this will be required as a tip, which we will call t. That effectively means that you want to spend as much money as you can, without going over (x - t).
What you want to do then, is define your targets:
double totalMoney = 190.0;
double minimumTip = totalMoney/115*15;
double targetMoney = totalMoney - minimumTip;
I'll assume that you have the required data structures, like so:
MenuItem[] items = new MenuItem[]
{
new MenuItem("Bandera Pizza Bread", 6.49),
new MenuItem("Boston's Pizza Bread", 5.35),
[...]
};
Now we want to search recursively for the best possible combination of these items, such that the total cost of the selected items is maximized while always remaining less than targetMoney.
Each branch of the recursive tree will represent one combination of products that I could purchase. This is the key difference between my solution and yours. At the first branch of the tree, I will evaluate two possibilities - either I will purchase "Bandera Pizza Bread", or I will not. At the second level of branches, I will evaluate whether I should purchase "Boston's Pizza Bread", or not. At each recursive call, I only need to know whether I still have any money left to spend (at which point I look at the next item down the list) or whether this order has 'overspent', at which point I give up on this combination (since buying anything else will just make it even more expensive!).
To reduce the number of arrays I need to create/discard, I'm using an integer "selected" as a bit field specifying which items I have decided to purchase on this branch. If a bit is 1, then I have chosen to purchase this item. If a bit is 0, then I have chosen not to purchase this item. You could get the same effect using arrays of booleans, but there would be a lot of array manipulation getting in the way of the actual algorithm I'm demonstrating.
I've also created class variables for the best case:
int bestPurchaseSet = 0;
double bestCost = 0;
You don't have to do this, you can pass your results around with parameters and return types, but it makes the code less heavy this way.
So then, the recursive function looks a bit like this:
public void search(MenuItem[] items,
int selected,
int depth,
double currentCost,
double maxCost)
{
if(currentCost > maxCost)
{
// too expensive
return;
}
if(currentCost > bestCost)
{
// New best combination! Save it.
bestCost = currentCost;
bestPurchaseSet = selected;
}
if(depth >= items.length)
{
// run out of food types
return;
}
// if we do choose this item, then we mark it as selected and increase the cost of this order.
search(items, selected | (0x1 << depth), depth + 1, currentCost + items[depth].cost, maxCost);
// if we don't choose this item
search(items, selected, depth + 1, currentCost, maxCost);
}
This should run quite efficiently, because each food item only adds one additional level of recursion - and many of the recursive branches are chopped off early (as soon as the purchase becomes too expensive).
Finally, it's a matter of printing out the results:
System.out.print("Best order for $" + totalMoney + " is: ");
for(int i=0; i<items.length; i++)
{
if((bestPurchaseSet & (0x1 << i)) != 0)
{
System.out.print(items[i].name + ", ");
}
}
System.out.println("The tip is " + (totalMoney - bestCost)/bestCost * 100 + "%");
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?