0

I am new to programming. Looked around the net and could not figure this problem out. Any help or explanation would be appreciated on why it keeps giving me an error.

Error: variable days might not have been initialized

import java.util.Scanner;

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

  Scanner keyboard = new Scanner(System.in);  
  int month, days;

  System.out.println("Enter the month: ");
  month = keyboard.nextInt();

  //month = ... // assume that we got this from the user
  if((month == 1)|| (month == 3) || (month == 5) || (month == 7) ||
     (month == 8) || (month == 10) || (month == 12))
    days = 31;
  else if ((month == 4)||(month == 6)||(month == 12))
    days = 30;
  else if (month == 2)
    days = 28;


  System.out.println("This month contains: "  +days + " days");
  }
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Istiak Khan
  • 173
  • 2
  • 2
  • 10
  • 1
    When you declare `days` you don't give it a value (i.e. you don't initialize it). You initialize it within your if/else if statements, however what happens if, say, month was equal to 56? None of your if/else if statements would trigger and days would still be undefined. Initialize `days` to something, or make sure there's a part of code that will DEFINITELY initialize it at some point. E.g., if after the last 'else if' just have an 'else' which initializes `days` to some default value. Or alternatively, initialize it when you declare it: `int days = -1` or some value – Jayce444 Sep 15 '17 at 22:56
  • Just give it some value. Like `int days = 0`. Its asking you to give it some default value. – eyoeldefare Sep 15 '17 at 23:00
  • [Why must local variables, including primitives, always be initialized in Java?](https://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java) - good read. – Manish Giri Sep 15 '17 at 23:01
  • Great, got it to work. Had to assign a value to days. Thanks :) – Istiak Khan Sep 15 '17 at 23:02

1 Answers1

0

You should include an else to fall back on if none of the conditions are met. This means that days will always be initialised.

Kyle Higginson
  • 922
  • 6
  • 11