分钟到年,天,小时和分钟对流



我的问题是我无法正确计算天数。帮帮我!

这是我的密码。

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分钟

我试着输入与问题示例相同的分钟数,以检查我的代码是否正确运行。

那么我在哪里失踪了。

对于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

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

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

我建议您使用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.

有关现代日期时间API的更多信息,请访问跟踪:日期时间

相关内容

  • 没有找到相关文章

最新更新