我正在制作24小时制

 林群东耀禎逸群 发布于 2023-02-13 20:40
  • php
  • 1 个回答
    • 数组所包含的int与变量中的int不同.是的,您使用变量初始化数组,但在此之后,数组int项目是独立的.如果要增加数组中的int项,则必须直接执行:myArray[someIndex]++.

      顺便说一下,根据我的评论,您是否不允许在此程序中使用面向对象的概念?这些说明是否强迫您使用静态做什么?我问这个的原因是因为一个更好的程序不会像你一样使用数组但是会有几秒钟,几分钟和几小时的int字段,并且会将逻辑封装在几秒到几分钟到几小时之间.这将是很多更容易维护和增强.


      编辑
      例如:

      public class FooClock {
         public static final int SECONDS_PER_MINUTE = 60;
         public static final int MINUTES_PER_HOUR = 60;
         private static final int NOON = 12;
         private int hours;
         private int minutes;
         private int seconds;
         private boolean am = true;
         private String formatString = "%02d:%02d:%02d %s";
      
         public FooClock(int hours, int minutes, int seconds, boolean am) {
            this.hours = hours;
            this.minutes = minutes;
            this.seconds = seconds;
            this.am = am;
         }
      
         public void incrementSeconds() {
            seconds++;
            normalize();
         }
      
         public void incrementMinutes() {
            minutes++;
            normalize();
         }
      
         public void incrementHours() {
            hours++;
         }
      
         public void normalize() {
            if (seconds >= SECONDS_PER_MINUTE) {
               minutes += seconds / SECONDS_PER_MINUTE;
               seconds %= SECONDS_PER_MINUTE;
            }
            if (minutes >= MINUTES_PER_HOUR) {
               hours += minutes / MINUTES_PER_HOUR;
               minutes %= MINUTES_PER_HOUR;
            }
            if (hours >= 2 * NOON) {
               hours %= (2 * NOON);
               am = true;
            }
            if (hours >= NOON) {
               am = false;
            }
         }
      
         @Override
         public String toString() {
            String amString = am ? "AM" : "PM";
            return String.format(formatString, hours, minutes, seconds, amString);
         }
      
         public static void main(String[] args) {
            int total_seconds = 24 * SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
      
            FooClock fooClock = new FooClock(0, 0, 0, true);
            System.out.println(fooClock);
            for (int i = 0; i < total_seconds; i++) {
               fooClock.incrementSeconds();
               System.out.println(fooClock + " ");
            }
         }
      }
      

      2023-02-13 20:44 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有