Java帮助;线太多了 [英] Java Help; too many Lines

查看:101
本文介绍了Java帮助;线太多了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//我需要程序来做它现在正在做的事情,但用更少的打印线。



//I need the program to do what it is doing right now, but with less Print lines.

public class AssignmentFour
{
    public static void main(String[] args)
    {
        final int MONDAY = 1;
        final int TUESDAY = 2;
        final int WEDNESDAY = 3;
        final int THURSDAY = 4;
        final int FRIDAY = 5;
        final int SATURDAY = 6;
        final int SUNDAY = 7;
        int day_of_week = 4;

        switch (day_of_week)
        {
        case MONDAY:
            System.out.println("Today's Monday!");
            break;
        case TUESDAY:
            System.out.println("Today's tuesday!");
            break;
        case WEDNESDAY:
            System.out.println("Today's wednesday!");
            break;
        case THURSDAY:
            System.out.println("Today's thursday!");
            break;
        case FRIDAY:
            System.out.println("Today's friday!");
            break;
        case SATURDAY:
            System.out.println("Today's Saturday!");
            break;
        case SUNDAY:
            System.out.println("Today's Sunday!");
            break;
        default:
            System.out.println("Invalid Data");
            break;
        }
    }
}

推荐答案

只需确保输入值介于1和7之间,然后只需使用日期名称查找数组中的值。



祝你好运!
Simply make sure the imput value is between 1 and 7, then simply lookup the value from an array with the names of the days.

Good luck!


Java 1.5及更高版本有枚举,这是一个干净的解决方案:

Java 1.5 and later has enum and this is the clean solution:
public class AssignmentFour
{
    enum DayOfWeek
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday,
    }

    public static void main(String[] args)
    {
        DayOfWeek dayOfWeek = DayOfWeek.Thursday;
        System.out.println("Today's " + dayOfWeek + "!");
    }
}



但教师可能对已推荐的阵列解决方案感兴趣。


But the teachers are probably interested in the array solution that was already recommended.


这听起来像家庭作业或类似的东西,但我会给你一个怀疑的好处。



尝试将你的日期名称存储在一个数组中,它减少了行数:



This sounds like homework or something similar, but I'm going to give you the benefit of the doubt on that one.

Try storing your day names in an array, it reduces the number of lines:

public static void main(String[] args)
{
    final String[] days = new String[] { "Monday", "tuesday", "wednesday", "thursday", "friday", "Saturday", "Sunday" };
    int day_of_week = 4;
    try {
       System.out.println(String.format("Today's %s!", days[day_of_week - 1]));
    }
    catch(IllegalArgumentException e) {
       System.out.println("Invalid Data");
    }
}



希望这会有所帮助,

Fredrik


Hope this helps,
Fredrik


这篇关于Java帮助;线太多了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆