Error: cannot Convert from double to float

Asked

Viewed 471 times

1

Why float is not accepted for numbers 0.197 and 0.185?

Code:

float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}   

ent.close();

1 answer

3


By default in java, floating point literal numbers are considered by JVM to be of the type double. You need to make it clear that that number is float, because the range of values of the double type is larger than the float type, and the JVM does not cast automatically in this case.

Just add a f next to the literal number, because this way you are explicitly stating that that literal value is also a float type:

float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197f);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185f);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.