Karavi - 6 months ago 36x

Java Question

I am fairly new to java and i was wondering how i might multiply a number a user inputs in a text box to a number they select in a combo box.

so far i have this:

`int Cost = Integer.parseInt(txtCost.getText());`

int TipCost;

int Tip = Integer.parseInt((String)cboTip.getSelectedItem());

TipCost = Cost*(Tip/100);

TipCost = Math.round(TipCost);

TipCost = TipCost/100;

What i get right now is just 0.

Answer

Your `TipCost`

needs to be of type `double`

in order to produce numbers that have a decimal point.

Also, your calculations are suffering from integer division, which disregards remainders. Calculations that divide an integer by 100 had better be with an integer greater than 100, or else the result will always be 0.

You also have some logic errors. Here is how you should fix your code:

```
int Cost = Integer.parseInt(txtCost.getText());
int Tip = Integer.parseInt(cboTip.getSelectedItem().toString());
double TipCost = Cost*Tip/100.0; // get the tip cost, 100.0 avoids integer division
TipCost = Math.round(TipCost*100)/100.0; // round to 2 decimal places
```

Source (Stackoverflow)

Comments