Solution:
At the time you convert double
to int
,the precision of the value is lost. For example, at the time you convert 4.8657 (double) to int.The int value will be 4.Primitive int
does not stocks decimal numbers.Hence you will lose 0.8657.
In your instance,0.7 is a double value(floating point employ as double by default if not mentioned as float-0.7f). At the time you calculate price*much*0.7
,the answer is a double value and hence the compiler wouldn't approve you to store it in a type integer because there could be a loss of precision. Hence that's what is possible lossy conversion
,you may lose precision.
So what could you do about it? You require to tell the compiler that you truly want to do it.You require to tell it that you know what you are doing. Therefore explicitly convert double to int employing the following code:
int total2= (int) price*much*0.7;
/*(int) tells compiler that you are aware of what you are doing.*/
//also called as type casting
In your instance,because you are calculating the cost,I'll suggest you to declare variable total2
as the type double or float.
double total2=price*much*0.7;
float total2=price*much*0.7;
//will work
There are many things wrong with that code, however the error you are getting is here:
amount = horsePower*0.746*rate*numberHours;
amount
is an integer, however the result of the expression on the right is a double (since the presence of floating point data "0.746" and "rate
" implies 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 obtain a zero as the result).
At the time you assign a double to an integer you lose information since you have to "throw away" anything to the right of the decimal point.
The compiler needs to be certain that you know what you are doing so it provides you an error to make confirm. You can do it, however you have to cast it first to avoid the error:
amount = (int) (horsePower * 0.746 * rate * numberHours);
However as has been mentioned, in case you instantly 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);