I need to initialize the variable with the value 0, why?

Asked

Viewed 92 times

0

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int codigo, quantidade;
        double preco;
        Scanner sc = new Scanner(System.in);
        codigo = sc.nextInt();
        quantidade = sc.nextInt();
        sc.close();
        switch (codigo) {
        case 1:
            preco = 4.0 * quantidade;
            break;
        case 2:
            preco = 4.5 * quantidade;
            break;
        case 3:
            preco = 5.0 * quantidade;
            break;
        case 4:
            preco = 2.0 * quantidade;
            break;
        case 5:
            preco = 1.5 * quantidade;
            break;
        }


System.out.printf("Total: R$ %.2f%n", preco);
    }

}

In the code thingy System.out.printf("Total: R$ %.2f%n", preco); indicates an error that in the boot snippet of the price variable double preco; I need to initialize it with 0 double preco = 0 but why can’t I initialize it without the value 0? Indicates this error: Exception in thread "main" java.lang.Error: Unresolved Compilation problem: The local variable preco may not have been initialized

at Main.main(Main.java:29)

1 answer

4


You don’t need to initialize preco with 0, but you need to ensure that this variable will be initialized before you print it on the screen.

See that in your code you initialize preco within a switch, but this only occurs if the value of codigo is equal to 1, 2, 3, 4 or 5.

And if the value of codigo for 6? preco will not initialize, and therefore the compiler returns an error.

You can add a clause default to ensure that codigo will always be initialized, so the compiler will accept your code.

switch (codigo) {
case 1:
    preco = 4.0 * quantidade;
    break;
case 2:
    preco = 4.5 * quantidade;
    break;
case 3:
    preco = 5.0 * quantidade;
    break;
case 4:
    preco = 2.0 * quantidade;
    break;
case 5:
    preco = 1.5 * quantidade;
    break;
default:
    preco = 0;
}

You can also treat this differently, such as returning an invalid code message to the user, just make sure that preco is initialized in some way.

Browser other questions tagged

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