【问题标题】:Number of Days Conversion in JavaJava中的天数转换
【发布时间】:2014-06-24 05:02:31
【问题描述】:

我需要使用模操作数将输入的天数转换为其等效的年/秒、月/秒、周/秒和天数。我们昨天才开始讨论,所以我还是有点生疏,但这是我制作的程序:

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);
}
}

我的算法是错的还是什么?

【问题讨论】:

  • 这既是“错误”又是“某事”。您是否希望能够仅基于year 计算出monthweekdays
  • 闰年呢?
  • 那么有 31 天的月份呢?还是28?最好使用joda-time
  • @RobbyCornelissen 即使是 Joda 也做不到。问题定义不够明确。
  • @DavidWallace 同意。需要有一个固定的瞬间。

标签: java days


【解决方案1】:

这将正常工作:

year = (double) (noOfDays/365);

    month=noOfDays/30.41;

   week=noOfDays/7;

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    如果您只是在没有闰年的一年内一个月内去一个固定的 30 days 365 days 那么您可以迭代到 for 循环中的天数并检查每个天数的模数用户输入的。

    样本:

        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);
    

    结果:

    Enter Number of Days: 330
    Year: 0
    Month: 11
    Week: 47
    Days: 330
    

    【讨论】:

    • 认真的吗?我听说过“除法作为迭代减法”,但从未听说过“除法作为迭代模运算符”。
    • 是的,我知道它有效。用脚趾甲剪修剪草坪也很有效。为什么不直接写months = noOfDays / 30; weeks = noOfDays / 7; years = noOfDays / 365; 而不是重新发明算术运算?
    • @DavidWallace 所以你的意思是(30天/7)=(4周)???对我来说似乎不合适。整数正在四舍五入。
    • 嗯,首先你说你的解决方案有效。现在你说它不起作用。它是哪一个?您的解决方案为 30 天内的周数提供 4
    【解决方案3】:

    这样做:

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多