Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot convert from double to float Error

I’m writing a simple program that converts pounds to kilos, but I’m a bit confused

import java.util.Scanner;

public class FiveTenOne {
    public static void main(String[] args)
    {
        Scanner keyboard =  new Scanner(System.in); //Creates Scanner Object

        System.out.print("Enter your weight in pounds: ");

        float pounds = keyboard.nextFloat();

        float kilos = pounds / 2.2;

        System.out.print("Your value in kilos is: " + kilos);

        keyboard.close();
    }
}

This is the code I wrote, all variables have been set to floats, yet it tells me that it cant convert from a double. at "pounds / 2.2;"

However when I write it like the code below "(float) (pounds / 2.2)" then no error comes back

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import java.util.Scanner;

public class FiveTenOne {
    public static void main(String[] args)
    {
        Scanner keyboard =  new Scanner(System.in); //Creates Scanner Object

        System.out.print("Enter your weight in pounds: ");

        float pounds = keyboard.nextFloat();

        float kilos = (float) (pounds / 2.2);

        System.out.print("Your value in kilos is: " + kilos);

        keyboard.close();
    }
}

Can someone explain to me why the first code doesn’t take it as a float?

or is it an IDE problem?

I tried both ways and know that the second one works fine, but I want to understand why exactly the first one doesn’t work

>Solution :

Double and Float are different data types, see e.g. Java: double vs float. The error message says that the division pounds / 2.2 returns a Double value. This value has to be cast to Float explicitly, just like you did in your second code example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading