-2

只是一个简短的程序,可以计算出用户输入的天数中的哪一天。我从星期六的第 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]);
        }
    }
}
4

5 回答 5

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)]);
于 2013-05-10T04:50:01.883 回答
2

从周日开始:

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

将大 if/else 替换为:

System.out.println(dayNames[numdays]);
于 2013-05-10T04:49:39.390 回答
1

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

喜欢

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

或者

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

那么你可以直接指定索引

System.out.println(dayNames[numdays]);
于 2013-05-10T04:48:23.237 回答
0

不需要循环

String dayNames[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
                "Sunday" };
int i  = (5 + numdays) % 7;
System.out.println(dayNames[i]);
于 2013-05-10T05:02:15.290 回答
0
for(numdays=0;numdays<=6;numdays++){
System.out.println(dayNames[(numdays + 6) % 7)]);
}
于 2013-05-10T04:49:31.820 回答