3

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...

Arctus
  • 33
  • 1
  • 6
  • local variable needs to be initialized `int month = 0;`.The compiler is saying if swich case is unable to initialize `month` then month doesnt have any value in that case you have to initialize it in the begining . – singhakash Feb 16 '16 at 05:29
  • You have another problem here. textmonth will be empty *always* – TheLostMind Feb 16 '16 at 05:33

6 Answers6

11

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.

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
6

When you declare month you should give it a default value (say 0 or -1), otherwise the JVM can't verify that month will be defined for all program paths leading to the print statement.

In this case, if an invalid month value was entered, what would the print statement output? Java can't tell. Java either needs a default value for every variable, or needs to be able to ensure that every possible program path assigns a value to the variable.

So you can either set month to have a value in int month (default value), or make your default case in the switch statement assign it a value (accounting for all program paths). This way, no matter what path the program takes, month will have a value when you try to print it.

Another option you may want to look at is throwing an error and terminating the program when an invalid month is given. Since you are not looping for input, a single invalid input will cause your output to be invalid as well. In this case, it might be preferable to signal the user that his/her input was wrong, and force them to start over, rather than allow their error to pass through to the output.

River
  • 8,585
  • 14
  • 54
  • 67
  • Out of curiosity, is it better if I initialize it at the same time I declare it, giving it a default value, or should I keep the declaration as it is and initialize it in the default case? Any convention I should follow? – Arctus Feb 16 '16 at 10:22
  • 1
    Both are perfectly valid, it really comes down personal preference. Personally I'd set it in the original declaration, and then have a check before the print statement to ensure a valid month was entered. This implies that if the month wasn't changed, then something went wrong. – River Feb 16 '16 at 16:06
2

The problem is int is a primitive types, all primitives types are not given default values when during runtime hence you are getting this error when trying to modify int without initializing it, unlike reference type whereas Java gives it it's default values.

As you can see in your default case you do not initialize the int variable month, hence for the compiler there is a possibility that the switch case will go to the default. If that occurs if you use the month variable after the case switch it does not have any default values hence the compiler error.

Actually if you pt month =0; or assign any value in default case it will compile okay.

You can read more: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html and: Java: Why am I required to initialize a primitive local variable?

Community
  • 1
  • 1
mel3kings
  • 8,857
  • 3
  • 60
  • 68
1

you need to guaranty that at run time no matter which value textmont has, month will get a value, now, take a look at the switch again ..

switch(textmonth) {
        case ("january"):
            month = 1;
            break;
...     

        case ("december"):
            month = 12;
            break;
        default:   //-< HERE is the point....
            System.out.println("The month you input was invalid");
        }

... and see that the default case has no assignment to the variable month..

then if that case occurs, month will have no initial value... add an correct assignment there and like others comment before, declare and init the variable,

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Try initializing the month

int month=0;

Scitech
  • 513
  • 1
  • 5
  • 16
0

Update your month declaration with this.

int month = 0;

If initialization is done in statements that might get only conditionally executed this error is thrown. Alternately, if you add a default statement that will also assign a value to month, it will compile fine.

Priyanka.Patil
  • 1,177
  • 2
  • 15
  • 34