我如何通过只使用一个if语句输入一个介于1和7之间的数字来确定现在是哪一天?

ubof19bj  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(330)
public static String GetDayOfWeek(int day){
        String weeks[]={"modnay","Tuesday","Wednesday","Thursday","Friday", "Saturday","Sunday"};
        int day1 = day-1 ;
        for(int i =0; i<weeks.length ; i++){
            if (day1 == weeks[i].lastIndexOf(i)){  // probably here is my mistake 
                return weeks[day1];
            }

        }
         return null;
}

如何比较输入数字和数组索引,以便找出哪一天?使用多态性还有其他方法吗?我想每天开一节课 extends 它到这个类,但然后我将使用多个如果!!
我被要求只使用一个if语句,不能使用多个if语句或switch语句。

bvpmtnay

bvpmtnay1#

public static String GetDayOfWeek(int day) {
    String weeks[] = {"Modnay", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    if (day > weeks.length || day < 0) {
        return null;
    }
    return weeks[day - 1];
}
rseugnpd

rseugnpd2#

只需返回正确索引处的元素,而无需任何循环。您可能还希望使数组成为静态的。如果这一天可能无效,您可以添加一个带有 if 声明。

public static String GetDayOfWeek(int day){
    String[] weeks = {"Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday","Sunday"};
    return day >= 1 && day <= 7 ? weeks[day - 1]: null;
}

相关问题