首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 計算課程結束時間與中場休息時間

     編輯:程式設計綜合問答

題目需求

  • 課程時長:2.5 小時(150 分鐘);
  • 中場休息:10 分鐘(第 70 分鐘開始);
  • 輸入:起始小時、分鐘;
  • 輸出:結束時間、休息開始/結束時間。

原代碼邏輯缺陷

int numberofhourbreakstart = (numberofh*60+numberofmin+classlength/2)/60; // ❌ classlength/2 = 75,非 70

休息時間計算硬編碼錯誤,且未處理分鐘進位邏輯。

推薦解法:使用 Calendar/Date API

import java.util.*;
import java.text.SimpleDateFormat;

public class LectureTime {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Hour: "); int h = sc.nextInt();
        System.out.print("Minute: "); int m = sc.nextInt();

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, h);
        cal.set(Calendar.MINUTE, m);
        cal.set(Calendar.SECOND, 0);

        // 休息開始:+70分鐘
        Calendar restStart = (Calendar) cal.clone();
        restStart.add(Calendar.MINUTE, 70);

        // 休息結束:+80分鐘
        Calendar restEnd = (Calendar) cal.clone();
        restEnd.add(Calendar.MINUTE, 80);

        // 課程結束:+150分鐘
        Calendar end = (Calendar) cal.clone();
        end.add(Calendar.MINUTE, 150);

        SimpleDateFormat fmt = new SimpleDateFormat("Hour: H\nMinute: m");
        System.out.println("This lecture will end at\n" + fmt.format(end.getTime()));
        System.out.println("The mid-lecture break start time is\n" + fmt.format(restStart.getTime()));
        System.out.println("The mid-lecture break end time is\n" + fmt.format(restEnd.getTime()));
    }
}

優勢

  • 自動處理跨小時、跨天進位;
  • 代碼清晰,避免手動時間運算錯誤;
  • 易擴展(如加入秒、時區)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved