How to calculate grand total servlet - java

Hi in my servlet I've got for loop to display content of cart, I want add to it "grand total" for all items in cart to calculate total for item I have
public double getTotalCost() {
return (getItemCount() * getItemPrice());
}
my for loop looks like
for (SimpleItem item : previousItems) {
out.println("<TR>"
+ "<TD>"+ item.getItemName() + "</TD>"
+ "<TD>"+ item.getItemArtistDirector() + "</TD>"
+ "<TD>"+ formatter.format(item.getItemPrice()) + "</TD>"
+ "<TD><DIV>"+ "<FORM id ='2' ACTION='OrderPage'>"
+ "<INPUT TYPE='HIDDEN' NAME='title' VALUE='" + item.getItemName()+ "'>"
+ "<INPUT TYPE='HIDDEN' NAME='artistDirector' VALUE='" + item.getItemArtistDirector()+ "'>"
+ "<INPUT TYPE='HIDDEN' NAME='price' VALUE='" + item.getItemPrice()+ "'>"
+ "<INPUT TYPE='TEXT' NAME='numItems' SIZE=3 VALUE='" + item.getItemCount() + "'>" + "<SMALL>"
+ "<button TYPE='SUBMIT' formaction = 'OrderPage'>Update Order</button>" + "</SMALL>"
+ "</FORM>" + "</DIV></TD>"
+ " <TD>"+ formatter.format(item.getTotalCost())+"</TD>"
+ "<TD>"+ item.getTotal() + "</TD>"
);
}
My question is how my method for grand total must looks like I have tried
public double getTotal(){
Double temp = getTotalCost();
if(getTotalCost()!=temp){
temp = temp + getTotalCost();
}
return(temp);
}

First, you forgot to close your TR there.
As for your grand total, you realize that a grand total is not something that applies to each item. It is the total sum of all the costs of all the items. So first, you are not supposed to display it in every row like you do the items.
Second, regarding your method: for the same reason, you cannot calculate a grand total in the class of a single item. You can only calculate a grand total when you can see the entire collection of items. So adding a method like that to SimpleItem like you have getTotalCost() is not going to work.
You could add it as a method to the servlet, by passing it the collection, looping and summing. But I suggest, since you are already looping, that you simply calculate the grand total while you are already looping.
So add a declaration before your loop:
double grandTotal = 0.0D;
And inside your loop, add:
grandTotal += item.getTotalCost()
At the end of the loop, you'll have a grand total. You'll need to display an extra row, where you'll put the grand total at the end, and only then to close with </TABLE>.
One last little note about your method: Don't declare a variable that's supposed to be used for calculations using a wrapper class like Double. Use double instead. Use wrapper classes only when you put things inside collections or otherwise need an Object. Using a temporary variable that is a Wrapper clase will cause the creation of many auto-box and auto-unbox objects and give the garbage collector a lot of work.

public double totalPrice(List<SimpleItem> items)
{
double price = 0d;
for (SimpleItem item : items)
{
price = price + item.getTotalCost();
}
return (price / items.size())
}

Related

How do you print variables? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
So I am working with this code but the end result should look something like this.
EX.
People: 4
Pizza: 1
Cost: $14.95
My code looks like this -
import java.util.*;
public class Pizza {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int people = keyboard.nextInt();
int pizza = people * 2 / 12 + 1;
double cost = pizza * 14.95;
System.out.println("People: " + people + "Pizzas: " + pizza + "Cost: $" + cost + );
}
}
The int people = keyboard.nextInt(); line allows me to input a integer value of people and the program then will take people * 2 and then divide by 12 (for the number of slices in a pizza) and + 1 to give me the pizzas I need. The cost will then be the pizza number * 14.95. I want the amount of people, pizzas, and cost to be displayed in the System.out.println method on the bottom. I do not know what I did wrong? Shouldn't + people + display the people in that line? Same with + pizza + and + cost + ?
The + operator joins strings (and other variables converted to strings). Just like in maths, you write it between two elements, so the final + was superfluous (and erroneous).
System.out.println("People: " + people + " Pizzas: " + pizza + " Cost: $" + cost);
When learning Java, you might want to use an IDE, which would point out this mistake for you, or just read the errors the compiler gives you.
You shouldn't have that last + at the end of your print statement, since there's nothing after it. When it's removed your code seems to run fine, albeit with a slight whitespace issue which you can fix by adding spaces to the print statement.
12
People: 12Pizzas: 3Cost: $44.849999999999994
System.out.println("People: " + people + "Pizzas: " + pizza + "Cost: $" + cost + );
You have put extra + at the end. Remove that.
String concatenation like str1 + str2 is OK, but pay attention to correctly print double value: you need only two fractional digits:
try (Scanner keyboard = new Scanner(System.in)) {
int people = keyboard.nextInt();
int pizza = people * 2 / 12 + 1;
double cost = pizza * 14.95;
System.out.printf(Locale.US, "People: %d, Pizzas: %d, Cost: $%.2f\n", people, pizza, cost);
}
Output:
10
People: 10, Pizzas: 2, Cost: $29.90

Can't remember how to do this for some reason

This one should be fairly simple I think, I just can't remember how, when using get methods of an object, how to pull the highest double out of the pack and put it in the println.
So far I just get every object to print with its percentages. But for the life of me I just can't remember and I know I've done this before.
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
Iterator<Book> it = books.iterator();
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
System.out.println("Highest markup is " + percent + " " + b.getTitle() + " " + b.getAuthor().getName().getLastName());
}
}
I'm pretty sure I need another local variable but I can't seem to do anything but make it equal the other percent. I have removed the other variable for now as I try to think about it.
I won't go into a lot of detail because it's homework (well done for being up-front about that, by the way) but here's the key idea: keep track of the largest percentage you've seen so far as your loop runs. That's what you want in your other variable.
Good job posting what you've tried so far. You were on the right track. As you loop through your books, keep a variables continuously updated with the highest percent seen so far and another variable for the associated book. Output the variable at the end outside the loop after iteration is done. Also, don't forget to check the edge case of an empty list of books! Something like this should do the trick:
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
if (books.size() == 0) {
return;
}
Iterator<Book> it = books.iterator();
double highestPercent = 0;
Book highestPercentBook = null;
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
if (percent > highestPercent) {
highestPercent = percent;
highestPercentBook = b;
}
}
System.out.println("Highest markup is " + highestPercent
+ " " + highestPercentBook.getTitle()
+ " " + highestPercentBook.getAuthor().getName().getLastName());
}

Java - Format number to print decimal portion only **without decimal**

This question was asked before (Formatting Decimal Number) without an answer as to how one can do such WITHOUT showing the decimal. I have been searching hours for an answer to no avail. Thanks in advance!
Example:
System.out.println("It would take " + oneMileMins + " minutes and " + oneMileDfSecs.format(oneMileSecs) + " seconds for the person to run one mile.");
Which outputs:
It would take x minutes and .yy seconds for the person to run one mile.
I would like the .yy to just be yy
Just change your output to oneMileDfSecs.format(oneMileSecs).replace(".", "")
EDIT: Rodney said that "He did not ask for the proper equation he only asked how to remove the decimal.", so I strike out the following , to respect him.
ADDITIONAL NOTE:
just like #Alan said , oneMileSecs should be equal to (int)((oneMile % 1)*60), in this case, the way you get rid of the decimal sign is little bit different :
1). If you declare :
double oneMileSecs = (int)((oneMile % 1)*60)
then change your output to :
String.valueOf(oneMileSecs).substring(0,String.valueOf(oneMileSecs).indexOf("."))
2). If you declare :
int oneMileSecs = (int)((oneMile % 1)*60)
then just output oneMileSecs directly as it's an int, it won't produce decimal sign
Not sure this is the answer you're looking for, as it doesn't answer the question in the title (Fev's answer does that), but I think this should give a correct result for the specific example:
private static void calcOneMile(double mph)
{
double oneMile = 60 / mph;
int oneMileMins = (int)oneMile;
double oneMileFraction = oneMile % 1;
int oneMileSecs = (int)(oneMileFraction * 60);
System.out.println("It would take " + oneMileMins + " minutes and " + oneMileSecs + " seconds for the person to run one mile.");
}
Or simplified to:
private static void calcOneMile(double mph)
{
int secondsToRunMile = (int)(1.0 / (mph / 3600));
System.out.println("It would take " + (secondsToRunMile / 60) + " minutes and " + (secondsToRunMile % 60) + " seconds for the person to run one mile.");
}

What am I doing wrong here? if statements not adding up

total in this case is 500. Trying to make a calculator, but not everything's adding up. It seems to skip the multiplication and just display total*amount. Is there something I'm doing wrong? EDIT: Discount: in the example, .92. I get 455000 if amount is 1000.
if (wShipping==true){
if (GroundShipping.isSelected()){
if (amount<=99) {
shipping=1.05;
output.setText(output.getText() + amount + "\t" + total*1.05*amount*discount + "\n");
}
else{
output.setText(output.getText() + amount + "\t" + total*amount*discount + "\n");
}
}
if (AirShipping.isSelected()){
shipping=1.1;
output.setText(output.getText() + amount + "\t" + total*amount*1.1*discount + "\n");
}
if (FedexShipping.isSelected()){
shipping=1.25;
output.setText(output.getText() + amount + "\t" + (total*amount*discount)*(1.25) + "\n");
}
}
You should consider the following things--
1) Why is the variable shipping needed if you are directly using the value in the set statement
2) Use else if statement since all the options are exclusive
3) You might want to check the initial values for variables and the formula for calculating the price. Taking the initial values as given, the lowest possible price is-
Price = 1000*500*0.92 = 460000 (total x amount x discount)
Hence there must be something amiss with your initial values
Maybe, just maybe is the first rule of currency calculations:
why not use double or float to represent currency

Altering variables inside ArrayList with double for loop

I have an ArrayList called participatingUsers. Person has Person.money and Person.name that are interesting.
What I want to do is check the ArrayList against itself...
So I have this code
for (Person debtHaver : this.participatingUsers) {
// If they're in debt...
if (debtHaver.getMoney() < 0) {
// With someone...
for (Person personToPay : this.participatingUsers) {
// That's not themselves...
if (!debtHaver.getName().equals(personToPay.getName())) {
// See if the personToPay is ranked higher than the
// debtHaver...
if (personToPay.getMoney() > 0) {
// If the debtee can pay the debter in full
if (-debtHaver.getMoney() <= personToPay.getMoney()) {
payment += debtHaver.getName() + " has to pay " + personToPay.getName() + " " + -debtHaver.getMoney() + "\n";
debtHaver.increaseMoney(-debtHaver.getMoney());
personToPay.decreaseMoney(-debtHaver.getMoney());
}
if (-debtHaver.getMoney() > personToPay.getMoney())
{
//But if he can't pay in full... Just pay the small bit you can pay.
payment += debtHaver.getName() + " has to pay " + personToPay.getName() + " " + personToPay.getMoney() + "\n";
debtHaver.increaseMoney(personToPay.getMoney());
personToPay.decreaseMoney(personToPay.getMoney());
}
}
}
}
}
}
return payment;
Basically, I have a double for loop where I check each person against itself. If someone is in debt and has a negative amount of money, seek if there is someone who they can pay, then pay that person. The thing is, personToPay is not being updated in the arrayList debtHaver is in. I'm basically editing two different ArrayLists instead of the same one. What's the best way to deal with this issue?
You are editing the same list. The problem is probably in this code:
debtHaver.increaseMoney(-debtHaver.getMoney());
personToPay.decreaseMoney(-debtHaver.getMoney());
You are putting debtHaver's amount to zero by the first line. And then you try to modify personToPay with zero amount. Just swap two lines of code and it should work:
personToPay.decreaseMoney(-debtHaver.getMoney());
debtHaver.increaseMoney(-debtHaver.getMoney());

Categories