Java (Find the future date with if else statements)

后端 未结 6 1586
故里飘歌
故里飘歌 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: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.");
    }
    

提交回复
热议问题