javainitializationswitch-statement

Why can't I initialize a variable inside a switch in Java?


I am just a beginner at programming, so I couldn't find my way around this. Existing questions seem to be either in other languages, or going over my head.

I am trying to write a small program for returning the week-specific day for any given date input.

import java.util.*;

class bday {
public static void main(String[] args){

    Scanner yearfinder = new Scanner(System.in);
    System.out.println("Please type any year");
    int year = yearfinder.nextInt();

    Scanner monthfinder = new Scanner(System.in);
    System.out.println("Please type any month");
    String textmonth = monthfinder.nextLine();
    int month;

    switch(textmonth) {
        case ("january"):
            month = 1;
            break;
        case ("february"):
            month = 2;
            break;
        case ("march"):
            month = 3;
            break;
        case ("april"):
            month = 4;
            break;
        case ("may"):
            month = 5;
            break;
        case ("june"):
            month = 6;
            break;
        case ("july"):
            month = 7;
            break;
        case ("august"):
            month = 8;
            break;
        case ("september"):
            month = 9;
            break;
        case ("october"):
            month = 10;
            break;
        case ("november"):
            month = 11;
            break;
        case ("december"):
            month = 12;
            break;
        default:
            System.out.println("The month you input was invalid");
        }

    Scanner datefinder = new Scanner(System.in);
    System.out.println("Please type any day");
    int date = datefinder.nextInt();

    System.out.println("The date you gave was " + date + "/" + month + "/" + year);
}
}

    //Jan 1 1900 was a monday.

Compiling this gives me an error that states that "variable month may not have been initialized", while pointing at "month" in the println statement. Is the initialization inside any of the cases invalid or something? I declared the month variable outside the switch...


Solution

  • Contrary to other replies, you do not need to initialize month at declaration.

    The problem is that if the textmonth is none of the literal values, the execution will fall to the default case, where month does not get initialized.

    You could initialize it to an invalid value, say 0 in the default case, but perhaps a better option is to give an error message and abort execution.