samedi 9 janvier 2016

Why doesn't this Java if statement work?

I want to return the date in yyyy-m-dd. But I don't understand why this doesn't work.

The error message:

java:42: error: variable mon might not have been initialized m = "" + mon;

My code:

public static String date() {
String s = Calendar.getInstance().getTime().toString();
String year, month, date, day, m;
int i, mon;

i = s.lastIndexOf(' '); // Find year.
year = s.substring(i, i + 5);

i = s.indexOf(' '); // Find month.
month = s.substring(i, i + 4);

if (month.equalsIgnoreCase("Jan"))
  mon = 1;
else if (month.equals("Feb"))
  mon = 2;
else if (month.equals("Mar"))
  mon = 3;
else if (month.equals("Apr"))
  mon = 4;
else if (month.equals("May"))
  mon = 5;
else if (month.equals("Jun"))
  mon = 6;
else if (month.equals("Jul"))
  mon = 7;
else if (month.equals("Aug"))
  mon = 8;
else if (month.equals("Sep"))
  mon = 9;
else if (month.equals("Oct"))
  mon = 10;
else if (month.equals("Nov"))
  mon = 11;
else if (month.equals("Dec"))
  mon = 12;

m = String.valueOf(mon);
day = s.substring(i + 5, i + 7); // Find day. 

date = year + "-" + m + "-" + day;
return date;

}

Aucun commentaire:

Enregistrer un commentaire