Java(使用 if else 语句查找未来日期)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12993698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:04:48  来源:igfitidea点击:

Java (Find the future date with if else statements)

javaif-statement

提问by Yigit Hatipoglu

I have a question that I can't figure it out , Thank you: Write a program that prompts the user to enter an integer for today's day of the week (Sunday is 0 ,Monday is 1 ,... and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week .Here is the sample run: Enter today's day: 1 Enter number of the day elapsed since today:3 Today is monday and the future day is thursday My try is:

我有一个我想不通的问题,谢谢:编写一个程序,提示用户输入星期几的整数(星期日是 0 ,星期一是 1 ,...星期六是 6) . 还提示用户为未来的一天输入今天之后的天数并显示一周中的未来一天。这是示例运行:输入今天的日期:1 输入自今天以来经过的天数:3 今天是星期一和未来的一天是星期四我的尝试是:

Scanner input = new Scanner(System.in);

System.out.print("Enter today's day (0 - 6):  ");
int day = input.nextInt();

System.out.print("Enter the number of days elapsed since today:  ");
int elapsed = input.nextInt();

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

System.out.print("Today is " + day + " and the future day is " + elapsed);

回答by fvu

As you need day-number to day-string twice, put it in a separate function. I want to show you a couple of possible approaches. Version 1, basic, simple and tidy:

由于您需要两次 day-number 到 day-string,请将其放在单独的函数中。我想向您展示几种可能的方法。版本1,基本、简单、整洁:

// isolate the daynumber --> daystring in a function, that's tidier
String dayFor (int daynumber) {
    String dayAsString = "ERROR";  // the default return value
    switch(dayNumber) {
        case 0 :
            dayAsString = "Sunday";
            break;
        case 1 :
            dayAsString = "Monday";
            break;
        // and so on, until
        case 6 :
            dayAsString = "Saturday";
            break;
     }
     return dayAsString;
}

A much shorter version that uses an array instead of the switch statement:

使用数组而不是 switch 语句的更短的版本:

String dayFor (int daynumber) {
    String dayStrings[] = new String[]{"Sunday","Monday", .... "Saturday"};
    // notice that daynumber's modulo is used here, to avoid index out of
    // bound errors caused by erroneous daynumbers:
    return dayStrings[daynumber % 7];
}

It might be tempting to try something along the lines of the following function where each case returns immediately, but having multiple return statements is discouraged. Just showing it here because it is technically possible, and you'll encounter it sometimes

尝试按照以下函数的方式进行操作可能很诱人,其中每个 case 立即返回,但不鼓励使用多个 return 语句。只是在这里展示它,因为它在技术上是可行的,你有时会遇到它

String dayFor (int daynumber) {
    switch(dayNumber) {
        case 0 :
            return "Sunday";
        case 1 :
            return "Monday";

        // and so on, until

        case 6 :
            return "Saturday";
     }
     // normally not reached but you need it because the compiler will
     // complain otherwise anyways.
     return "ERROR";
}

After this rather long intro the main function becomes short and simple. After the input you just need:

在这个相当长的介绍之后,主要功能变得简短而简单。输入后,您只需要:

// present day + elapsed modulo 7 = the future day
int future = (day + elapsed) % 7;
System.out.print("Today is " + dayFor(day) + " and the future day is " + dayFor(future) );

Don't forget to add code to check your inputs!

不要忘记添加代码来检查您的输入!

回答by AnandFrancis

The question gives you the days ranging from 0-6, instead of 1-7(conventional). Now, for example, if the day today is 1(Monday) and the daysElapsed since today is 3, then the day should be Thursday. Since this question has the initial day inclusive, the resulting day will be after 1(Monday),2,3(Wednesday) have passed, that is Thursday.

该问题为您提供了 0-6 天,而不是 1-7 天(常规天数)。现在,例如,如果今天是 1(星期一)并且从今天起经过的天数是 3,那么这一天应该是星期四。由于此问题包含第一天,因此结果一天将在 1(星期一)、2,3(星期三)过去之后,即星期四。

Let's take an example and apply it to the code below.

让我们举一个例子并将其应用到下面的代码中。

day = 1;

天 = 1;

daysElased = 3;

天数 = 3;

else if(day > 0 && day < 7) , which is the case

else if(day > 0 && day < 7) ,就是这种情况

{

{

sum = 1(day) + 3(daysElapsed); // sum = 4

sum = 1(day) + 3(daysElapsed); // 总和 = 4

}

}

If sum is in the range of 0-6, each if case can be created corresponding to each day. In the case above, the sum is less than 6, so it will be having its own if clause. Had the sum been greater, for example, days = 1 and daysElapsed = 6, then sum = 1(days) + 6(daysElapsed) = 7.

如果 sum 在 0-6 的范围内,则可以创建每个 if case 对应于每一天。在上述情况下,总和小于 6,因此它将有自己的 if 子句。如果总和更大,例如,days = 1 和 daysElapsed = 6,则 sum = 1(days) + 6(daysElapsed) = 7。

In this case it will match the clause if(sum > 6), then sum = sum % 7 = 7 % 7 = 0 = Sunday. This means that the days from 1(Monday) to 6(Saturday) have been elapsed, so the day will be Sunday(0).

在这种情况下,它将匹配 if(sum > 6) 子句,然后 sum = sum % 7 = 7 % 7 = 0 = Sunday。这意味着从 1(星期一)到 6(星期六)的日子已经过去了,所以这一天将是星期日(0)。

if(day == 0) // If the present day entered is Zero(0 is for Sunday)
{
    sum = daysElapsed;    // daysElapsed will be entered by the user
}

else if(day > 0 && day < 7)    // If the present day is > 0 but < 7 (1 - 6 days)
{
    sum = day + daysElapsed;    // 
}

if(sum>6)    // if 0<= sum <=6 , 6 if cases can be created. If sum > 6 :
{
    sum = sum % 7;
}

if(sum == 0)
{
    System.out.println("Day is Sunday.");
}
.
.
.
.
else if(sum == 6)
{
    System.out.println("Day is Saturday.");
}

回答by j.doe

The question is from a book titled "Introduction to Java programming" by Y. Daniel Liang. Apart from using the string type, which I believe is covered in the next chapter; the solution I wrote for this exercise uses only what you have been taught so far.

问题来自Y. Daniel Liang 的一本名为“ Java 编程简介”的书。除了使用string type 之外,我相信这将在下一章中介绍;我为此练习编写的解决方案仅使用了您目前所学的内容。

import java.util.Scanner;

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

        System.out.print("Enter today's day: ");
        int todaysDay = input.nextInt();

        System.out.print("Enter the number of days elapsed since today: ");
        int elapsedDays = input.nextInt();

        int futureDay = (todaysDay + elapsedDays) % 7;
        String day_of_week = "";

        switch (todaysDay) {
            case 0: day_of_week = "Sunday"; break;
            case 1: day_of_week = "Monday"; break;
            case 2: day_of_week = "Tuesday"; break;
            case 3: day_of_week = "Wednesday"; break;
            case 4: day_of_week = "Thursday"; break;
            case 5: day_of_week = "Friday"; break;
            case 6: day_of_week = "Saturday";
        }

        switch (futureDay) {
            case 0:
                System.out.println("Today is " + day_of_week + " and the future day is Sunday."); break;
            case 1:
                System.out.println("Today is " + day_of_week + " and the future day is Monday."); break;
            case 2:
                System.out.println("Today is " + day_of_week + " and the future day is Tuesday."); break;
            case 3:
                System.out.println("Today is " + day_of_week + " and the future day is Wednesday."); break;
            case 4:
                System.out.println("Today is " + day_of_week + " and the future day is Thursday."); break;
            case 5:
                System.out.println("Today is " + day_of_week + " and the future day is Friday."); break;
            case 6:
                System.out.println("Today is " + day_of_week + " and the future day is Saturday.");
        }
    }
}

Output:

输出:

Enter today's day: 0
Enter the number of days elapsed since today: 31
Today is Sunday and the future day is Wednesday.

Notes:

笔记:

  • The first switch statement assigns a day of type string to the variable day_of_weekwhich is later used for printing "today's day".

  • To obtain the future day, you must find the remainder of the sum of today's day and the number of days elapsed divided by 7.

  • The last switch statement "matches" a case number that is identical to the number stored within the futureDayvariable (which is obtained by performing the mathematical operation noted above).

  • 第一个 switch 语句将字符串类型的一天分配给变量day_of_week,该变量稍后用于打印“今天的一天”。

  • 要获得未来的一天,您必须找到今天的天数和经过的天数之和除以 7 的余数。

  • 最后一个 switch 语句“匹配”一个 case 编号,该编号与存储在futureDay变量(通过执行上述数学运算获得)中的编号相同。

回答by Bhesh Gurung

You can do it better by using an array to store the the day names.

您可以通过使用数组来存储日期名称来做得更好。

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

Now you can use the user input as the index

现在您可以使用用户输入作为索引

int nameIndex = //... get input
//validate input
//dayNames[nameIndex] is the day of the week

Now get the input for number of days to add

现在获取要添加的天数的输入

int numDays = //...get input

Then just add that many days to compute the index for future day of week

然后只需添加那么多天来计算未来一周的索引

int futureNameIndex = nameIndex; //start with entered day of week index
for(int i=0; i<numDays; i++) {
    futureNameIndex++; //increment by 1 for numDays times
    if(futureNameIndex == dayNames.length) { //if the index reaches lenght of the array
        futureNameIndex = 0;                 //reset it to 0
    }
}

I think you will find that one easier to understand. Finally

我想你会发现它更容易理解。最后

//dayNames[futureNameIndex] is the future day of week.

回答by Haggra

As I know, this question is from the book "Introduction To Java Programming". Where this question is asked, you don't have any knowledge of methods, loops, arrays etc. so I will just use Selections.

据我所知,这个问题来自“Java编程简介”一书。在问这个问题的地方,您对方法、循环、数组等一无所知,所以我将只使用选择。

Here, when I tried to solve with a better way, I could not find any since we cannot use arrays which could be very helpful or methods which is even better. That's why this question is a little redundant in book.

在这里,当我尝试用更好的方法解决时,我找不到任何方法,因为我们无法使用可能非常有用的数组或更好的方法。这就是为什么这个问题在书中有点多余。

And you really should not use if statements because switch is much better in this case.

你真的不应该使用 if 语句,因为在这种情况下 switch 更好。

    System.out.println("Enter today's number (0 for Sunday, 1 for Monday...) :");
    int todayNo = in.nextInt();

    System.out.println("Enter the number of days elapsed since today:");
    int elapsedDay = in.nextInt();

    int futureDay = (todayNo + elapsedDay) % 7;

    switch (todayNo) {
        case 0:
            System.out.print("Today is Sunday and");
            break;
        case 1:
            System.out.print("Today is Monday and");
            break;
        case 2:
            System.out.print("Today is Tuesday and");
            break;
        case 3:
            System.out.print("Today is Wednesday and");
            break;
        case 4:
            System.out.print("Today is Thursday and");
            break;
        case 5:
            System.out.print("Today is Friday and");
            break;
        case 6:
            System.out.print("Today is Saturday and");
            break;

    }

    switch (futureDay) {
        case 0:
            System.out.print(" the future day is Sunday.");
            break;
        case 1:
            System.out.print(" the future day is Monday.");
            break;
        case 2:
            System.out.print(" the future day is Tuesday.");
            break;
        case 3:
            System.out.print(" the future day is Wednesday.");
            break;
        case 4:
            System.out.print(" the future day is Thursday.");
            break;
        case 5:
            System.out.print(" the future day is Friday.");
            break;
        case 6:
            System.out.print(" the future day is Saturday.");
            break;

    }

Here, the only thing that you maybe don't know is System.out.print();. The only difference with the System.out.println(); is with this method, this one doesn't print on a new line, it prints on the same line which is what we need here. Tinker with it to understand better.

在这里,您可能唯一不知道的是 System.out.print();。与 System.out.println() 的唯一区别;使用这种方法,这个方法不会在新行上打印,而是在我们需要的同一行上打印。修改它以更好地理解。

回答by yash chowdary

package javaapplication2;

import java.util.Scanner;
public class JavaApplication2 {


    public static void main(String[] args) {

    int day, eday, fday;
        String str, str1;
        Scanner S = new Scanner(System.in);
        System.out.println("Enter today's day: ");
        day = S.nextInt();
        System.out.println("Enter the number of days elapsed since today: ");
        eday = S.nextInt();
        if (day == 0) {
            str = "Sunday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 1) {
            str = "Monday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 2) {
            str = "Tuesday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 3) {
            str = "Wednesday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 4) {
            str = "Thursday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 5) {
            str = "Friday";
            System.out.print("Today is " +str + " and ");
        }
        else if (day == 6) {
            str = "Saturday";
            System.out.print("Today is " +str + " and ");
        }

       fday = day + eday;

       if (fday % 7 == 0) {
            str1 = "Sunday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 1) {
            str1 = "Monday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 2) {
            str1 = "Tuesday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 3) {
            str1 = "Wednesday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 4) {
            str1 = "Thursday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 5) {
            str1 = "Friday";
            System.out.print("Future day is " +str1);
        }
        else if (fday % 7 == 6) {
            str1 = "Saturday";
            System.out.print("Future day is " +str1);
        }

    }