分钟到年、天、小时和分钟的转换

ncecgwcz  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(1054)

我的问题是我不能正确地计算出天数。帮帮我!
这是我的密码。

package basic.programs;

import java.util.Scanner;

public class MinutesToYearDaysConversion {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int Minutes, Years, MinutesRemain, Days, MinutesRemainAfterDays, Hours, MinutesRemainAfterHours;

        System.out.print("give the minutes : ");
        Minutes = sc.nextInt();
        Years = Minutes / 535600;
        MinutesRemain =  Minutes % ( 535600);
        Days = MinutesRemain / 1440;
        MinutesRemainAfterDays =  MinutesRemain % (1440 );
        Hours =  MinutesRemainAfterDays / 60;
        MinutesRemainAfterHours = MinutesRemainAfterDays % (60);
        System.out.print("Given minutes has" + Years + "years" + Days +  "days" + Hours +  "hours and " + MinutesRemainAfterHours +  "minutes ");
    }
}

输出:-

give the minutes : 3000010
Given minutes has 5 years 223 days14 hours and 50 minutes

//编写一个java程序将分钟数转换成年、日、小时和分钟数。
//例如:输入:分钟=3000010输出:给定分钟有5年258天8小时10分钟
我试着输入问题给出的分钟数作为示例来检查我的代码是否正确运行。
所以我错过了什么。

o7jaxewo

o7jaxewo1#

对于java中包含的功能来说,这是一个非常神奇的数字 TimeUnit . 不幸的是,它不能提供 toYears() (你的数学假设一年正好是365天)。不管怎样,这可以用类似的方法来实现

Scanner sc = new Scanner(System.in);
System.out.print("give the minutes : ");
int origMinutes = sc.nextInt();
long days = TimeUnit.MINUTES.toDays(origMinutes);
long years = days / 365;
days -= years * 365;
long hours = TimeUnit.MINUTES.toHours(origMinutes
        - TimeUnit.DAYS.toMinutes(years * 365)
        - TimeUnit.DAYS.toMinutes(days));
long minutes = origMinutes
        - TimeUnit.DAYS.toMinutes(years * 365)
        - TimeUnit.DAYS.toMinutes(days)
        - TimeUnit.HOURS.toMinutes(hours);
System.out.printf("Given minutes has %d years %d days %d hours and %d minutes%n",
        years, days, hours, minutes);

运行示例输入,生成示例输出。

give the minutes : 3000010
Given minutes has 5 years 258 days 8 hours and 10 minutes
z9zf31ra

z9zf31ra2#

我建议你用 java.time.Duration . 我还建议您遵循java命名约定,例如变量, Minutes, Years, MinutesRemain 等应命名为 minutes, years, minutesRemain 等。

import java.time.Duration;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter minutes: ");
        int mins = sc.nextInt();
        Duration d = Duration.ofMinutes(mins);
        long days = d.toDaysPart();
        long hours = d.toHoursPart();
        long minutes = d.toMinutesPart();
        System.out.print("Given minutes has " + days / 365 + " years " + days % 365 + " days " + hours + " hours and "
                + minutes + " minutes.");
    }
}

示例运行:

Enter minutes: 3000010
Given minutes has 5 years 258 days 8 hours and 10 minutes.

在trail:date-time了解有关现代日期时间api的更多信息。

nle07wnf

nle07wnf3#

一年有525600分钟,而不是535600分钟。

Years = Minutes / 525600;
MinutesRemain =  Minutes % ( 525600);

相关问题