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
Related
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());
}
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.");
}
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())
}
I am using real type to save price value in SQLite database but it does not return correctly value. If I save a few values like 1.01 it will return 4.029999999999999.
I have read that best way to save prices in SQLite is to use integer type
But I don't know how to use it.
How to store and retrieve prices in this case?
Here code how I retrieve price now:
Cursor cursor = null;
double totalPrice = 0;
try {
cursor = mDB.rawQuery("select " + Expense.PRICE + " from " + Expense.TABLE_NAME + " where " + " (strftime("
+ dateType + ", " + Expense.DATE + "))" + "= ? ", new String[] { currentDate });
} catch (Exception e) {
Log.e(TAG, "error" + e.toString());
e.printStackTrace();
}
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
totalPrice += cursor.getDouble(cursor.getColumnIndex(Expense.PRICE));
}
It is actually quite simple when you see it.
I don't know what currency you are in, but assume US $.
You want to store $1.01. This is the same as 101 cents. You just multiply by 100.
So before storing the number, multiply by 100.
When displaying the number, divide by 100.
Just to add to that answer: I also think you should store the numbers in memory as cents/integers too. So for all your workings, calculations etc, use that integer format.
If a user enters a $ amount, convert it straight away into integer (multiply by 100). And only change back to $ when you need to display it.
In other words, not just when going to and from the database.
Effective Java book describes, in Item 48, that one should not use float or double if exact answers is required.
I think you should use long value to store the price value, but store the values in "cents" (or equivalent as per currency of choice) instead of "dollars". This way your math around prices should work just fine with no loss due to floating-point arithmetic.
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());