15,511,078 members
2.00/5 (1 vote)
See more:
if (unit >= 1 && unit <=200){
rate = 0.218;
}
else if (unit >= 201 && unit <= 800){
rate = 0.345;
}
else {
rate = 0.421;
}
amount = horsePower*0.746*rate*numberHours;
amount = sc.nextInt();
System.out.println ("amount to pay is =" + amount);

What I have tried:

i have tried to compile it and it still have error in my calculation. Can you help me ?
Posted
Updated 10-Nov-18 22:33pm
Dave Kreskowiak 10-Nov-18 22:53pm
You haven't provided enough details about the problem. You give no description of the error, what the code is supposed to do, the inputs you're using, the expected outputs, ...
Manish K. Agarwal 10-Nov-18 23:02pm
Also you tagged it as JavaScript while it looks like as JAVA code. What are the data type of amount, horsepower, rate etc. why are you overwriting the amount with next input using sc.nextInt()

## Solution 1

There are many things wrong with that code, but the error you are getting is here:
`amount = horsePower*0.746*rate*numberHours;`

`amount` is an integer, but the result of the expression on the right is a double (because the presence of floating point data "0.746" and "`rate`" means that it all gets "promoted" to floating point even if "`horsePower`" and "`numberHours`" are integer - it it wasn't then the floating point would have to be truncated to an integer and your alway get a zero as the result).
When you assign a double to an integer you lose information because you have to "throw away" anything to the right of the decimal point.

The compiler wants to be sure that you know what you are doing so it gives you an error to make sure. You can do it, but you have to cast it first to avoid the error:
`amount = (int) (horsePower * 0.746 * rate * numberHours);`

But as has been mentioned, if you immediately overwrite the value with the user input it's pretty irrelevant!
```amount = horsePower*0.746*rate*numberHours;
amount = sc.nextInt();  // <---- Move or remove this!
System.out.println ("amount to pay is =" + amount);```

But do yourself a favour and stop using "magic numbers" - they don't make code at all easy to understand or maintain.

## Solution 2

Quote:
i have tried to compile it and it still have error in my calculation.

How do you know that there is an error in calculation?
Java
```amount = horsePower*0.746*rate*numberHours;         // 1) here you do some calcylation
amount = sc.nextInt();                              // 2) here you replace it with user input
System.out.println ("amount to pay is =" + amount); // 3) so, here you print the user input```

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 96 Richard MacCutchan 80 Richard Deeming 80 k5054 45 merano99 40
 OriginalGriff 929 Richard Deeming 808 Richard MacCutchan 751 Dave Kreskowiak 200 merano99 195

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900