0

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.

Elysium
  • 145
  • 1
  • 4
  • 15

1 Answers1

1

nextInt() does not consume the ENTER after the year is entered, so nextLine() consumes it, leaving you with an empty string. One way around this is to always use nextLine():

int year = Integer.valueOf(in.nextLine());

Alternatively, you can just use another nextLine() after consuming the int:

int year = in.nextInt();
in.nextLine(); // To get rid of the additional \n
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • thanks a lot! This resolved the issue. So basically nextLine() takes the value entered before pressing return key. – Elysium Oct 18 '14 at 15:07