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?
CodePudding user response:
init your int hasil = 0;
or assign a value for it in the default
case
default:
hasil = 0;
System.out.println("Operator tidak valid");
CodePudding user response:
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.