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

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

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

  1. package basic.programs;
  2. import java.util.Scanner;
  3. public class MinutesToYearDaysConversion {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int Minutes, Years, MinutesRemain, Days, MinutesRemainAfterDays, Hours, MinutesRemainAfterHours;
  7. System.out.print("give the minutes : ");
  8. Minutes = sc.nextInt();
  9. Years = Minutes / 535600;
  10. MinutesRemain = Minutes % ( 535600);
  11. Days = MinutesRemain / 1440;
  12. MinutesRemainAfterDays = MinutesRemain % (1440 );
  13. Hours = MinutesRemainAfterDays / 60;
  14. MinutesRemainAfterHours = MinutesRemainAfterDays % (60);
  15. System.out.print("Given minutes has" + Years + "years" + Days + "days" + Hours + "hours and " + MinutesRemainAfterHours + "minutes ");
  16. }
  17. }

输出:-

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

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

o7jaxewo

o7jaxewo1#

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

  1. Scanner sc = new Scanner(System.in);
  2. System.out.print("give the minutes : ");
  3. int origMinutes = sc.nextInt();
  4. long days = TimeUnit.MINUTES.toDays(origMinutes);
  5. long years = days / 365;
  6. days -= years * 365;
  7. long hours = TimeUnit.MINUTES.toHours(origMinutes
  8. - TimeUnit.DAYS.toMinutes(years * 365)
  9. - TimeUnit.DAYS.toMinutes(days));
  10. long minutes = origMinutes
  11. - TimeUnit.DAYS.toMinutes(years * 365)
  12. - TimeUnit.DAYS.toMinutes(days)
  13. - TimeUnit.HOURS.toMinutes(hours);
  14. System.out.printf("Given minutes has %d years %d days %d hours and %d minutes%n",
  15. years, days, hours, minutes);

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

  1. give the minutes : 3000010
  2. Given minutes has 5 years 258 days 8 hours and 10 minutes
展开查看全部
z9zf31ra

z9zf31ra2#

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

  1. import java.time.Duration;
  2. import java.util.Scanner;
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. System.out.print("Enter minutes: ");
  7. int mins = sc.nextInt();
  8. Duration d = Duration.ofMinutes(mins);
  9. long days = d.toDaysPart();
  10. long hours = d.toHoursPart();
  11. long minutes = d.toMinutesPart();
  12. System.out.print("Given minutes has " + days / 365 + " years " + days % 365 + " days " + hours + " hours and "
  13. + minutes + " minutes.");
  14. }
  15. }

示例运行:

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

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

展开查看全部
nle07wnf

nle07wnf3#

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

  1. Years = Minutes / 525600;
  2. MinutesRemain = Minutes % ( 525600);

相关问题