Hello, new to Java and I've been doing some coding for a few weeks. Right now I am stumped. I've been trying to make a program that would display how many days are in the month when the user inputs a month number, but it keeps saying that

DaysInMonth.java:64: error: variable days might not have been initialized
JOptionPane.showMessageDialog(null,days);

Whenever I set days to a like a placeholder number like 1, I get one back. Any ideas on how to fix this?

import javax.swing.JOptionPane;

public class DaysInMonth {


    public static void main(String[]args) {

    String inputString = JOptionPane.showInputDialog("Input your month number");
    int month = inputString.charAt(0);

    inputString = JOptionPane.showInputDialog("Input your year number");
    int year = inputString.charAt(0);

    int days;
    switch (month) {

    case 1: days = 31;
    break;

    case 2:  
      if (year % 4 == 0)
            days = 28;
      else days = 29;
    break;
    case 3: days = 31;

    break;
    case 4: days = 30;

    break;
    case 5: days = 31;

    break;
    case 6: days = 30; 

    break;
    case 7: days = 31;

    break;
    case 8: days = 31;

    break;
    case 9: days = 30;

    break;
    case 10: days = 30;

    break;
    case 11: days = 31;
    break;

    case 12: days = 31;

   }

  JOptionPane.showMessageDialog(null,days);       
   }
}

Add a "default" case to handle the 31 day months (since they make up more than half of them), and remove those individual cases, and it will also ensure that your variable gets a value.

The reason you get that error is because what hapens if the user enters a number that doesn't match any of those options? What would be the value then. In fact, you should probably keep all of the indivudual case options, and add a default option setting the value to -1 and check for that value (after the switch) to determine that the input was valid.

In fact, what is happening is that the integer value of the character at string index 0 falls OUTSIDE of those options, as the char integer value of the String "1" is NOT 1. Use Integer.parseInt(String).

In line 14 change int days; to int days = 0; or whatever value you want to initialize it to. You really should do some input validation, then your switch statement becomes more predictable, and there won't be the possibility of invalid values. Right now I can enter values such as 'a', 'b', etc..

Questions: What do you want to do if user enters 1 or more (non-numeric) characters? What do you want to do if user enters a digit > 1 or < 1 for month? What about year?

Edited 2 Years Ago by cgeier

This article has been dead for over six months. Start a new discussion instead.