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
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.