Here's my code:
package Random;
import java.util.Scanner;
public class SwitchMonth {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Year: ");
int year = in.nextInt();
System.out.println("Enter month: ");
String month = in.nextLine();
//String month = ""
switch (month) {
case "january":
case "march":
case "may":
case "july":
case "august":
case "october":
case "december":
System.out.println("No. of days: 31");
break;
case "april":
case "june":
case "september":
case "november":
System.out.println("No. of days: 30");
break;
case "february":
if ((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0))
System.out.println("No. of days: 29");
else
System.out.println("No. of days: 28");
break;
default:
System.out.println("Wrong month entered.");
break;
}
in.close();
}
}
Output:
Enter year: 2000
Enter month:
Wrong month entered.
The program terminates without taking the month input. If i hard code the month name then it's working fine but when i take the input from console it terminates with above output. I believe the problem lies with Scanner object. If i use another Scanner object for month then it's working fine.
So my question is: Can i use same scanner object for taking int input then string input or not?? if not then why??
All the answers are appreciated. Thanks in advance.