任何人都可以使用循环缩短此代码吗?

时间:2013-05-10 04:45:24

标签: java loops weekday

只是一个简短的程序,可以确定用户输入的天数中的哪一天。我从星期六的第6天开始。有没有办法可以使用循环缩短代码?

import java.util.Scanner;

class Week{
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        int days[] = {1,2,3,4,5,6,7,8};
        String dayNames[] = {"Monday","Tuesday","Wednesday","Thursday","Friday",
                "Saturday", "Sunday"};
        int numdays;

        System.out.println("Enter how many days from now: ");
        numdays = input.nextInt();

        numdays = (6 + numdays) % 7;

        if(numdays == 0){
            System.out.println(dayNames[6]);
        }
        else if(numdays == 1 ){
            System.out.println(dayNames[0]);
        }
        else if(numdays == 2){
            System.out.println(dayNames[1]);
        }
        else if(numdays == 3){
            System.out.println(dayNames[2]);
        }
        else if(numdays == 4){
            System.out.println(dayNames[3]);
        }
        else if(numdays == 5){
            System.out.println(dayNames[4]);
        }
        else if(numdays == 6){
            System.out.println(dayNames[5]);
        }
    }
}

5 个答案:

答案 0 :(得分:3)

以下部分:

if(numdays == 0){
    System.out.println(dayNames[6]);
}
else if(numdays == 1 ){
    System.out.println(dayNames[0]);
}
else if(numdays == 2){
    System.out.println(dayNames[1]);
}
else if(numdays == 3){
    System.out.println(dayNames[2]);
}
else if(numdays == 4){
    System.out.println(dayNames[3]);
}
else if(numdays == 5){
    System.out.println(dayNames[4]);
}
else if(numdays == 6){
    System.out.println(dayNames[5]);
}

...简单地替换为:

System.out.println(dayNames[(numdays + 6) % 7)]);

答案 1 :(得分:2)

从星期日开始:

String dayNames[] = {"Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday",
            "Saturday"};

将大if / else替换为:

System.out.println(dayNames[numdays]);

答案 2 :(得分:1)

您可以使用switch个案而不是多个if语句

switch(numdays) {
  case 1:  ....  break;
  case 2: ..... break;
.....
}

String dayNames[] = {"Sunday", "Monday","Tuesday","Wednesday","Thursday",
  "Friday","Saturday"};

然后你可以直接指定索引

System.out.println(dayNames[numdays]);

答案 3 :(得分:0)

for(numdays=0;numdays<=6;numdays++){
System.out.println(dayNames[(numdays + 6) % 7)]);
}

答案 4 :(得分:0)

不需要循环

String dayNames[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
                "Sunday" };
int i  = (5 + numdays) % 7;
System.out.println(dayNames[i]);