So I've got my code working so far, but I've got two problems. this code lets you put in a month, day, and year and it tells you how many days it has. essentially it's a leap-year checker but includes every month (for whatever reason).
Right now the only way I know to make cases work is to use numbers, but I want the user to be able to type the actual name of the month as input and the code still knows which case to take it to. when I try to name the case month names it says it doesn't recognize the variable. so that's my first problem.
My second problem is if the user tries to input characters into the "Year" section that aren't integers, I want it to give an error message. someone told me to use .hasNextInt() but I'm totally unsure of the functionality of it or how to implement it. I've looked at other people's code on here trying to figure out how it's used to no avail. here's my code, any suggestions or guidance would be greatly appreciated. thank you in advance!
public class MonthLength {
public static void main(String[] args) {
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
int month = Integer.parseInt(userInput);
// Terminate program if month is not a proper month name
if (month < 1 || month > 12) {
System.out.println("Illegal month name; try again");
return;
}
// Prompt the user to enter a year
SimpleIO.prompt("Enter a year: ");
userInput = SimpleIO.readLine();
int year = Integer.parseInt(userInput);
//Terminate program if year is not an integer
if (year < 0) {
System.out.println("Year cannot be negative; try again");
return;
}
// Determine the number of days in the month
int numberOfDays;
switch (month) {
case 2: // February
numberOfDays = 28;
if (year % 4 == 0) {
numberOfDays = 29;
if (year % 100 == 0 && year % 400 != 0)
numberOfDays = 28;
}
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
numberOfDays = 30;
break;
default: numberOfDays = 31;
break;
}
// Display the number of days in the month
System.out.println("There are " + numberOfDays +
" days in this month");
}
}