-1

I am trying to write a program that will get a date from the user and the user can enter the month

  • as a String ("july")
  • or as a number (7).

The code works fine when the user gives an integer for the month but when the user gives the month as a string the program says:

Exception in thread "main" java.util.InputMismatchException

and then ends. I think theres a syntax error or something in the main method but I am not sure...

Sorry I included so much of my code... I don't really know where the problem is.

import java.util.*;

public class DateHoliday{
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        //declare varaiables for month, day and year
        int monthNumber, day, year;
        String, monthString, holiday;

        System.out.print("This program will ask you for a month, day, and year\n");
        System.out.print("and will print the corresponding date in two standard date formats.\n");
        int repeat = kb.nextInt();

         //ask the user how many times to run the code
        System.out.print("How many times do you want to run the code:");
        for (int i = 1; i <= repeat; i++){
            //prompt the user to enter the month
            System.out.print("Please note, you may enter the month as:\nA numeric value (1-12)\n");
            System.out.print("an unabbreviated month name (January etc....)\nEnter the month:");
            //check to see if the user is entering an integer for the month
            if(kb.hasNextInt()) {
                //read the month as an integer
                monthNumber = kb.nextInt();
                //call the method to convert the month to a string
                getMonthString(monthNumber);
            } else {
                //read the month as a String
                monthString = kb.nextLine();
                //call the method to convert it to an integer
                monthNumber = getMonthNumber(monthString);//I THINK THIS IS THE PROBLEM
            }

            //get the day from the userS ;
            System.out.print("Enter the day:");
            day = kb.nextInt();

            //get the year from the user;
            System.out.print("Enter the year:");
            year = kb.nextInt();

            // call the method to get the holidays assosiated with the given date
            // display the desired output in the given format
            holiday = getHoliday(monthNumber, day, year);
            System.out.println("The Date is: FIXMONTH/"+day+"/"+year+" FIXMONTH "+day+", "+year+"  "+holiday);
        }
    }

    public static String getMonthString(int monthNumber) {
        String result = "";
        switch(monthNumber) {
            case 1:  result = "january";   break;
            case 2:  result = "february";  break;
            case 3:  result = "march";     break;
            case 4:  result = "april";     break;
            case 5:  result = "may";       break;
            case 6:  result = "june";      break;
            case 7:  result = "july";      break;
            case 8:  result = "august";    break;
            case 9:  result = "september"; break;
            case 10: result = "october";   break;
            case 11: result = "november";  break;
            case 12: result = "december";  break;
        }
        return result;
    } 

    public static int getMonthNumber(String monthString) {
        String lowerMonth = monthString.toLowerCase();
        int result = 0;

        switch(lowerMonth) {
            case "january":   result = 1;  break;
            case "february":  result = 2;  break;
            case "march":     result = 3;  break;
            case "april":     result = 4;  break;
            case "may":       result = 5;  break;
            case "june":      result = 6;  break;
            case "july":      result = 7;  break;
            case "august":    result = 8;  break;
            case "september": result = 9;  break;
            case "october":   result = 10; break;
            case "november":  result = 11; break;
            case "december":  result = 12; break;
        }
        return result;
    } 

Thanks so much! I actually needed kb.nextLine(); after monthString = kb.nextLine(); but i would not of figured that out without you guys! Im going to see if i can work out how to add the months to the output correctly on my own....wish me luck

  • Check whether this code `monthString = kb.nextLine()` print the actual data ? – Santhosh Oct 30 '14 at 09:25
  • possible duplicate of [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – ifloop Oct 30 '14 at 09:26

3 Answers3

1

The method Scanner#nextLine() consumes and returns the input till the next line break. The line break itself is not consumed.

So when the user enters a month in it's word form (e.g. "May") the following will happen (I simplified our code) :

// ...

if(kb.hasNextInt()) {                              // <- this will evaluate to false
    monthnumber = kb.nextInt()
    getMonthString(monthnumber);
} else {
    monthNumber = getMonthNumber(kb.nextLine());   // <- this will read "May"
}

//get the day from the userS ;
System.out.print("Enter the day:");  
day = kb.nextInt();                                // <- this will read the "\n" from the Month input. CRASH.

// ...

In order to fix that, you just have to consume the linebreak manually:

// ...

if(kb.hasNextInt()) {                              // <- this will evaluate to false
    monthnumber = kb.nextInt()
    getMonthString(monthnumber);
} else {
    monthNumber = getMonthNumber(kb.nextLine());   // <- this will read "May"
    in.nextLine();                                 // consume the "\n"
} 

// ...
ifloop
  • 8,079
  • 2
  • 26
  • 35
0

Your Problem has a simple solution, use kb.next() instead of kb.nextLine():

change

//read the month as a String monthString = kb.nextLine();

to

//read the month as a String monthString = kb.next();

nextLine does something different, that you don't want. Also there are a few other strange things in your code:

  • delete the first "," in line 8 so you get:String monthString, holiday;
  • close your Scanner in the end: kb.close();
  • change line 25 from getMonthString(monthNumber);

    to monthString = getMonthString(monthNumber);

  • exchange line 12 and 15 from:

int repeat = kb.nextInt(); //ask the user how many times to run the code System.out.print("How many times do you want to run the code:");

to

System.out.print("How many times do you want to run the code:"); //ask the user how many times to run the code int repeat = kb.nextInt();

Adrodoc
  • 673
  • 10
  • 19
-1

First of All, you need to no about nextInt() method behavior.

You have to press "enter" key after giving input.

For example to give 7 as input you need to press 7 after that you need to click on "enter" button to read given input(i.e,7). So, your input like this 7\n

But, nextInt() method will read only 7 and not "\n". So, to capture "\n", you need to place nextLine() method after nextInt() method is used.

So, place nextLine() statement as a next statement to nextInt() as mentioned below

monthNumber = kb.nextInt();
kb.nextLine();
Karthik
  • 76
  • 7