Java使用if语句和kb.hasNextInt / kb.nextLine来查找用户是否输入了字符串或整数

时间:2014-10-30 09:21:47

标签: java if-statement methods return switch-statement

我正在尝试编写一个程序,该程序将从用户获取日期,用户可以输入月份

  • 作为String"july"
  • 或作为数字(7)。

当用户给出月份的整数时,代码正常工作,但当用户将月份作为字符串时,程序会说:

  

线程“main”中的异常java.util.InputMismatchException

然后结束。我认为主语法中存在语法错误或其他问题,但我不确定......

抱歉,我收录了很多代码......我真的不知道问题出在哪里。

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;
    } 

非常感谢!我实际上需要kb.nextLine();在monthString = kb.nextLine()之后;但如果没有你们,我不会想到这一点!我将看看我是否可以解决如何在我自己正确添加月份输出....祝我好运

3 个答案:

答案 0 :(得分:1)

方法Scanner#nextLine()使用并返回输入直到下一个换行符。换行本身不会消耗。

因此,当用户输入一个月的单词形式(例如&#34; May&#34;)时,会发生以下情况(我简化了代码):

// ...

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.

// ...

为了解决这个问题,您只需手动使用换行符:

// ...

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"
} 

// ...

答案 1 :(得分:0)

您的问题有一个简单的解决方案,使用kb.next()而不是kb.nextLine():

变化

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

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

nextLine做了不同的事情,你不想要。您的代码中还有一些其他奇怪的东西:

  • 删除第8行中的第一个“,”,以便获得:String monthString, holiday;
  • 最后关闭您的扫描仪:kb.close();
  • getMonthString(monthNumber);

    更改第25行

    monthString = getMonthString(monthNumber);

  • 交换第12和15行:

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:");

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();

答案 2 :(得分:-1)

首先,你不需要关于nextInt()方法的行为。

输入后必须按“enter”键。

例如,为了输入7作为输入,你需要按7然后你需要点击“输入”按钮来读取给定的输入(即7)。那么,你的输入是这样的 7 \ n

但是,nextInt()方法只读取7而不是“\ n”。因此,要捕获“\ n”,需要在使用nextInt()方法之后放置nextLine()方法。

因此,将nextLine()语句作为nextInt()的下一个语句放置,如下所述

monthNumber = kb.nextInt();
kb.nextLine();