1

I have this problem wherein I have to convert kilometers into miles. I'm a novice programmer so bear with me.

Here's my code so far:

import java.util.Scanner;

public class problem1 {
    public static void main (String args[]) {
        float m;
        float km;

        Scanner input=new Scanner(System.in);

        System.out.print("Please enter a distance in kilometers:");
        km=input.nextFloat();
        m=km*0.621371;
        System.out.println("This is equal to: "+m);
    }
}

It gives me an error saying:

Incompatible types:possible lossy conversion from double to float.
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Oreo
  • 33
  • 1
  • 6
  • HINT: Floating point numbers are by default of `double` type. – Rohit Jain Feb 12 '15 at 17:52
  • 1
    if you want to use float use f at the end like 0.621371f – Anil Feb 12 '15 at 17:52
  • I'm guessing you mean lossy conversion? Have you tried googling the error? http://stackoverflow.com/questions/21645783/possible-lossy-conversion-from-double-to-float-given-float-values – Adrian Leonhard Feb 12 '15 at 17:52
  • 1
    In addition to what you'll learn from the answers, also learn that formatting and coding conventions are very important for communication with your fellow programmers (including those reading your code in the future). Class names should begin with a capital letter, and the code blocks should be properly indented. – RealSkeptic Feb 12 '15 at 17:55

3 Answers3

3

You are trying to set a double to a float variable

To fix, change this line

m=km*0.621371;

to

m=km*0.621371f;
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • It is consider a bad programming practice to use magic numbers. By only looking at this code you can not tell what does 0.621371 mean? – Sigismundus Feb 12 '15 at 18:19
1

The value 0.621371 is a double literal, so the km values is promoted to double when multiplied. Storing the double product back to m would be a conversion that could lose data (double to float).

To keep the data as a float, use a float literal, with a f on the end:

m=km*0.621371f;

Normally a double for the results would be just fine, so you could also just change the datatypes of m and km to double.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

You need to define constant variable as a float, since km is read as a float.

final float KM_TO_ML = 0.621371F;
m = km * KM_TO_ML;
Sigismundus
  • 635
  • 4
  • 15