I wrote this code to calculate the valid day entry—- and in the process i experimented with nesting the switch statement inside the if else statement… in the switch statement.. i further added an if else statement…
And was pretty happy.. with it.. until i .. well.. Compiled it 🙁
it’s giving like 50 errors.. or something… So is this type of nesting invalid??
What all nesting is valid?
The code is as follows
public DateFour(int m,int d,int y){
if (y<2011 && y>0){
year=y;
if{
switch(m){
case 1:case 3 case 5: case 7:case 8:case 10: case 12:
month=31;
if (day>0 && day<=31){
day=d;
System.out.println("The date today is:"+day"/"+month+"/"+year);
}
else{
System.out.println("invalid date");
}
break;
case 2:
month=28;
if (day>0 && day<=28){
day=d;
System.out.println("The date today is:"+day"/"+month+"/"+year);
}
else{
System.out.println("invalid date");
}
break;
case 4:
case 6:
case 9:
case 11:
month =30;
if (day>0 && day<=30){
day=d;
System.out.println("The date today is:"+day"/"+month+"/"+year);
}
else{
System.out.println("invalid date");
}
default:
System.out.println("Invalid month.");
}
}
}
else{
System.out.println("invalid input");
}
}
That is not a valid construct in Java.
ifwhat?You’re missing a
:in there. Please use spacing consistently.All your print statements are missing a
+afterday.Otherwise, yes, you can nest switch and if. It just gets unreadable very, very fast (as you have just noticed).