Java (Find the future date with if else statements)

后端 未结 6 1540
故里飘歌
故里飘歌 2020-12-22 14:39

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 ,

相关标签:
6条回答
  • 2020-12-22 15:09
    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);
            }
    
        }
    
    0 讨论(0)
  • 2020-12-22 15:14

    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.

    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_week which 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 futureDay variable (which is obtained by performing the mathematical operation noted above).

    0 讨论(0)
  • 2020-12-22 15:15

    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:

    // 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:

    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

    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!

    0 讨论(0)
  • 2020-12-22 15:15

    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.
    
    0 讨论(0)
  • 2020-12-22 15:16

    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.

    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.

        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.

    0 讨论(0)
  • 2020-12-22 15:18

    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.

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

    day = 1;

    daysElased = 3;

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

    {

    sum = 1(day) + 3(daysElapsed); // sum = 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.

    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(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.");
    }
    
    0 讨论(0)
提交回复
热议问题