Reputation: 97
I am getting an error message when I try to make a switch with a String. Here is the error:
incompatible types found:
java.lang.String
required: int
switch(monthName){
This makes it seem like I can only make a switch with an int but I was pretty sure that in the more recent Java versions you can make a switch with a String. Here's the code that is giving me the error:
switch(monthName){
case "December"://Always has 31 days
daysLeft = 31;
daysLeft -= dayOfMonth;
break;
case "November"://Always has 30 days
daysLeft = 61;
daysLeft -= dayOfMonth;
break;
case "October"://Always has 31 days
daysLeft = 92;
daysLeft -= dayOfMonth;
break;
case "September"://Always has 30 days
daysLeft = 122;
daysLeft -= dayOfMonth;
break;
Upvotes: 0
Views: 63
Reputation:
Define enum in your class:
public enum MonthName {
December, November, October, September
}
Use val variable to provide switch functionality on basis of string input-
String val = "December";//can be taken from user through Scanner class
MonthName monthName = MonthName.valueOf(val);//Enum class object
switch (monthName) {
case December://Always has 31 days
daysLeft = 31;
daysLeft -= dayOfMonth;
break;
case November://Always has 30 days
daysLeft = 61;
daysLeft -= dayOfMonth;
break;
case October://Always has 31 days
daysLeft = 92;
daysLeft -= dayOfMonth;
break;
case September://Always has 30 days
daysLeft = 122;
daysLeft -= dayOfMonth;
break;
}
System.out.println(dayOfMonth + "---" + daysLeft);//Test of output
}
Upvotes: 0
Reputation: 26067
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum constants are permitted
Upvotes: 2