我如何获得新的价值以回溯if语句

时间:2018-09-17 20:39:22

标签: java if-statement switch-statement

我正在尝试获取直到会议返回的天数并打印出新会议开始的日期,但是我一直在获取整数而不是字符串。

import java.util.Scanner;
public class NextMeeting {
    public static void main(String [] args) {
        int day, daysToMeeting = 0;
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the day of the week 0-6: ");
         day = scan.nextInt();
        System.out.println("Enter the days to meeting: ");
        daysToMeeting = scan.nextInt();

        if (day == 0) {
            System.out.println("Today is Sunday");
        } else if (day == 1) {
            System.out.println("Today is Monday");
        }
        else if (day == 2) {
            System.out.println("Today is Tuesday");
        }
        else if (day == 3) {
            System.out.println("Today is Wednesday");
        }
        else if (day == 4) {
            System.out.println("Today is Thursday");
        }
        else if (day == 5) {
            System.out.println("Today is Friday");
        }
        else if (day == 6) {
            System.out.println("Today is Saturday");
        }

        System.out.println("Today is: " + day);


        if( daysToMeeting >= 6) {
            day = daysToMeeting - 7;
        }
        else {
            day = day + 6;
        }
        System.out.println("Days to the meeting is " + daysToMeeting + " +days.");
        System.out.println("Meeting day is : " + Integer.toString(day));
    }
}

几天的输出仍然是3,但是我们需要在星期三打印出来。我不知道该如何实现。

3 个答案:

答案 0 :(得分:0)

您可以使用DayOfWeek枚举。

System.out.println("Meeting day is : " + DayOfWeek.of(day).toString());

您还可以删除嵌套的if-else语句,并使用DayOfWeek枚举来显示“今天是xyz-day”。

答案 1 :(得分:0)

您正在打印整数,因为day是一个整数。可能效率不高,但一个简单的解决方法是创建一个String变量,然后在daysToMeeting if-else块下面的另一个if语句块中,将String分配给每个对应的整数,例如

String meetingDay;
if(day == 1){
    meetingDay = "Monday";
}

,然后使用String变量打印出来。

System.out.println("Meeting day is : " + meetingDay);

答案 2 :(得分:0)

只需创建一个方法,该方法将通过传递day int返回星期几。然后打印结果。

public String intToDayName(int day) {
            if(day > 6) {
                day = day % 7; 
            }
           if (day == 0) {

                return "Sunday"; 
            } else if (day == 1) {
                return "Monday";
            }
            else if (day == 2) {
                return "Tuesday"; 
            }
            else if (day == 3) {
                return "Wednesday";
            }
            else if (day == 4) {
                return "Thursday";
            }
            else if (day == 5) {
                return "Friday";
            }
            else if (day == 6) {
                return "Saturday";
            }
           return "Error";

    }

在照片中调用它:

System.out.println("Meeting day is : " + intToDayName(daysToMeeting));
System.out.println("Today is " + intToDayName(day));

如果您实际上希望代码返回并打印第一个if-else语句,那么我建议循环。