如何在该程序中添加“小于”语句

时间:2019-09-05 19:24:54

标签: switch-statement

我的任务是使用switch语句创建一个程序,以根据月份中的确切天数打印月份名称。如果输入的天数与任何月份都不对应,则程序还需要显示“错误”消息。我的代码实现了这两个目标。但是,我想知道是否存在一种较短的方法,当用户输入的数字小于28时,使用“小于”语句来获取“错误”消息

import java.util.Scanner;

public class months {

public static void main(String[] args) {

    Scanner keyboard  = new Scanner(System.in);
    int numb_days = 0;
    System.out.println("Enter the # of days");
    numb_days = keyboard.nextInt();

    //This program will print 'May' when you run it.
    String monthName;
    switch (numb_days) {
        case 30:  monthName = "April, June, September, November ";
            break;
        case 31:  monthName = "January, March, May, July, August, November, October, December ";
            break;
        case 28:  monthName = "February";
            break;
        case 29:  monthName = "February (only on leap years)";
            break;
        case 1:  monthName = "Unknown";
            break;
        case 2:  monthName = "Unknown";
            break;
        case 3:  monthName = "Unknown";
            break;
        case 4:  monthName = "Unknown";
            break;
        case 5:  monthName = "Unknown";
            break;
        case 6: monthName = "Unknown";
            break;
        case 7: monthName = "Unknown";
            break;
        case 8: monthName = "Unknown";
            break;
        case 9:  monthName = "Unknown";
            break;
        case 10:  monthName = "Unknown";
            break;
        case 11:  monthName = "Unknown";
            break;
        case 12:  monthName = "Unknown";
            break;
        case 13:  monthName = "Unknown";
            break;
        case 14: monthName = "Unknown";
            break;
        case 15: monthName = "Unknown";
            break;
        case 16: monthName = "Unknown";
            break;
        case 17:  monthName = "Unknown";
            break;
        case 18:  monthName = "Unknown";
            break;
        case 19:  monthName = "Unknown";
            break;
        case 20:  monthName = "Unknown";
            break;
        case 21:  monthName = "Unknown";
            break;
        case 22: monthName = "Unknown";
            break;
        case 23: monthName = "Unknown";
            break;
        case 24: monthName = "Unknown";
            break;
        case 25:  monthName = "Unknown";
            break;
        case 26:  monthName = "Unknown";
            break;
        case 27: monthName = "Unknown";
            break;
        default: monthName = "Unknown";
            break;
    }
    System.out.println(monthName);
    }
}

1 个答案:

答案 0 :(得分:0)

默认语句足以处理28-31的特定情况未捕获的所有其他情况。因此,您可以删除所有其他情况1-27。

如果需要使用小于语句,则可以在使用switch语句之前使用它:

if (numb_days < 28) {
   month_name = "unknown";
} else {
   // Switch statement goes here
}