Java (Find the future date with if else statements)

后端 未结 6 1544
故里飘歌
故里飘歌 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: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.

提交回复
热议问题