Variable might not have been initialized error (I don't know what to do after 20 minutes of research)

Viewed 36

I am currently learning Java, and I am making a very basic calculator just to really get into it. The problem here is that "variable (ergebnis, zeichen_switch) might not have been initialized" and it seems that it MIGHT not have been initialized, because the initialization can only be one out of 4 different possibilities.

import java.io.*;
public class Rechner {
    public static void main(String[] args) throws IOException {
        //Zahl 1
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String zahl1_e = br.readLine();
        int zahl1 = Integer.parseInt(zahl1_e);
        //Rechenzeichen
        InputStreamReader isr0 = new InputStreamReader(System.in);
        BufferedReader br0 = new BufferedReader(isr0);
        String zeichen = br0.readLine();
        //Zahl 2
        InputStreamReader isr1 = new InputStreamReader(System.in);
        BufferedReader br1 = new BufferedReader(isr1);
        String zahl2_e = br1.readLine();
        int zahl2 = Integer.parseInt(zahl2_e);
        //Rechnung
        int zeichen_switch;
        if (zeichen.equals("+")) {
            zeichen_switch = 0;
        }
        if (zeichen.equals("-")) {
            zeichen_switch = 1;
        }
        if (zeichen.equals("*")) {
            zeichen_switch = 2;
        }
        if (zeichen.equals("/")) {
            zeichen_switch = 3;
        }
        int ergebnis;
        switch (zeichen_switch) {
            case 0:
                ergebnis = zahl1 + zahl2;
            case 1:
                ergebnis = zahl1 - zahl2;
            case 2:
                ergebnis = zahl1 * zahl2;
            case 3:
                ergebnis = zahl1 / zahl2;
        }
        System.out.println("Das Ergebnis ist: " + zahl1 + " " + zeichen + " " + zahl2 + " " + ergebnis);
    }
}

The problem occurs at the last print-command and at the variable that tells the switch which case to take.

Thanks in advance

1 Answers

What happens if zeichen_switch is not one of the four operators? ergebnis is never given a value, you should add a default case to your switch. Java is just making sure ergebnis will actually be assigned a value, which is why you're getting that error.

int zeichen_switch = -1;
if (zeichen.equals("+")) {
    zeichen_switch = 0;
}
if (zeichen.equals("-")) {
    zeichen_switch = 1;
}
if (zeichen.equals("*")) {
    zeichen_switch = 2;
}
if (zeichen.equals("/")) {
    zeichen_switch = 3;
}
int ergebnis = -1;
switch (zeichen_switch) {
    case 0:
        ergebnis = zahl1 + zahl2;
    case 1:
        ergebnis = zahl1 - zahl2;
    case 2:
        ergebnis = zahl1 * zahl2;
    case 3:
        ergebnis = zahl1 / zahl2;
    default:
        ergebnis = 0;
}

Note zeichen_switch is also assigned a value.

Related