-1

I've initialized the variable I wanted, but after adding it's values through a switch case, I cannot return it. Is there any solutions?`


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Masukkan nilai a = ");
        int a = input.nextInt();

        System.out.print("Masukkan nilai b = ");
        int b = input.nextInt();

        System.out.print("Mau diapain bang angkanya? ");
        String o = input.next();

        int hasil;
        switch (o) {
        case "+":
            hasil = a + b;
            break;
        case "-":
            hasil = a - b;
            break;
        case "*":
            hasil = a * b;
            break;
        case "/":
            hasil = a / b;
            break;
        default:
            System.out.println("Operator tidak valid");
        }

// Error is here, stating that I haven't initialized the variable
        System.out.println(hasil);

    }
}

`

I've tried putting the console out in each of the case, and it did worked. So, is my first way of doing it is not working?

eevcxx
  • 11
  • 2
  • 1
    Assign it a default value when you declare it, or give it one in the default branch. The issue is that it might not be initialized if none of those cases trigger. – Edward Peters Nov 22 '22 at 03:16

2 Answers2

1

It shows that error because you declared them but didn't initialized them.

Your variable should be initialized as int hasil = 0;

Check this reference for a better idea. This user has explained it very smoothly.

0

init your int hasil = 0; or assign a value for it in the default case

default:
  hasil = 0;
  System.out.println("Operator tidak valid");
Tan Sang
  • 320
  • 2
  • 10