Number of Days Conversion in Java

2019-09-06 08:44发布

I need to use the modulo operand to convert an inputted number of days to its equivalent number of year/s, month/s, week/s, and days. We just started discussion yesterday so I'm still a bit rusty but this is the program I made:

import java.util.Scanner;

public class DaysConvert {
   public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int noOfDays, year, month, week, days;

    System.out.print("Enter Number of Days: ");
    noOfDays = input.nextInt();

    year = noOfDays/365;
    month = year%365;
    week = month%30;
    days = week%7;

    System.out.println("Year: " + year);
    System.out.println("Month: " + month);
    System.out.println("Week: " + week);
    System.out.println("Day: " + days);
}
}

Is my algorithm wrong or something?

标签: java days
3条回答
冷血范
2楼-- · 2019-09-06 09:16

Do it like this:

public class DaysConvert
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int noOfDays, year, month, week, days;

        System.out.print("Enter Number of Days: ");
        noOfDays = input.nextInt();

        year = noOfDays/365;
        noOfDays=noOfDays%365;

        month = noOfDays/30;
        noOfDays=noOfDays%30;

        week = noOfDays/7;
        noOfDays=noOfDays%7;


        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Week: " + week);
        System.out.println("Day: " + noOfDays);
    }
}
查看更多
Viruses.
3楼-- · 2019-09-06 09:30

If you are just going to a fixed 30 days in a month 365 days in a year with no leap year then you can iterate to the number of days in a for-loop and check the modulo of each one from the the user's inputted.

sample:

    for(int i = 1; i < noOfDays+1; i++)
    {
        if((i %30) == 0)
            month++;
        if((i%7) == 0)
            week++;
        if((i%365) == 0)
            ++year;
        if((i%1) == 0)
            days++;

    }

    System.out.println("Year: " + year);
    System.out.println("Month: " + month);
    System.out.println("Week: " + week);
    System.out.println("Days: " + days);

result:

Enter Number of Days: 330
Year: 0
Month: 11
Week: 47
Days: 330
查看更多
啃猪蹄的小仙女
4楼-- · 2019-09-06 09:38

This will work properly:

year = (double) (noOfDays/365);

    month=noOfDays/30.41;

   week=noOfDays/7;

i hope this helps.

查看更多
登录 后发表回答