Trying to learn java but problems like this confuse me

Sarcasm

Well-Known Member
Joined
Jul 13, 2009
Messages
220
Reaction score
2
Hi, can someone please help me with this as I'm still a noob to this.

When i do this using ints it works fine but as soon as I use doubles it fails.

double price = 0, total = 0;

for (int i = 1; i <= 3; i++)
{
price= Double.parseDouble(JOptionPane.showInput… enter price"));
price+=total;

}

System.out.print("Total = " +total);

Now it loops 3 times if I enter "2" three times with that using Ints it prints Total = 6. Using doubles it shows up as Total = 0.0.

Any help would be appreciated,

Thanks
 
Inside the loop, your last line of code is:

price += total

This should rather be

total += price

...remember that the variable that you're setting (total) should be the one to the left of the = sign, and the value (price) to which you're setting that variable should be on the right.

That way, the variable "total" will be incremented by value "price" each time the loop loops.
 
Top
Sign up to the MyBroadband newsletter
X