【问题标题】:How do I get the military time difference to read correctly?如何正确读取军事时差?
【发布时间】:2016-09-04 12:52:52
【问题描述】:

我正在尝试编写一个程序,其中控制台告诉一个人两次没有 IF 语句的时间之间的差异,在“军事时间”或 24 小时时间。到目前为止,我有:

import java.util.Scanner;

public class MilTimeDiff {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the first time: ");
        String time1 = s.next();
        System.out.print("Enter the second time: ");
        String time2 = s.next();
        String tm1 = String.format("%02d", Integer.parseInt(time1));
        String tm2 = String.format("%02d", Integer.parseInt(time2));
        int t1 = Integer.parseInt(tm1);
        int t2 = Integer.parseInt(tm2);
        int difference = t2 - t1;
        while (t1 < t2) {
            String tmDif = Integer.toString(difference);
            System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
                    tmDif.substring(1) + " minutes.");
            break;
        }
    }

}

但我有两个问题:一:如果我将时间一 0800 和时间二 1700,它给了我正确的 9 小时。但如果相差 10 小时或更多,它给出了 1 小时和很多分钟。我认为使用 String.format 方法会有所帮助,但它没有做任何事情。

二:我不知道如何处理时间 1 晚于时间 2 的情况。

谢谢!

【问题讨论】:

  • 你有没有错,错的逻辑? Enter the first time: 13 Enter the second time:343 The difference between times is 3 hours 30 minutes.

标签: java


【解决方案1】:

你可以试试下面的代码,它会给出军事格式的时差:

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the first time: ");
    String time1 = s.next();
    System.out.print("Enter the second time: ");
    String time2 = s.next();
    String tm1 = String.format("%02d", Integer.parseInt(time1));
    String tm2 = String.format("%02d", Integer.parseInt(time2));

    String hrs1 = time1.substring(0, 2);
    String min1 = time1.substring(2, 4);
    String hrs2 = time2.substring(0, 2);
    String min2 = time2.substring(2, 4);

    // int difference = t2 - t1;
    if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
        int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
        int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
        if (minDiff < 0) {
            minDiff += 60;
            hrsDiff--;
        }

        System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");

    } else {
        int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
        int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
        if (minDiff < 0) {
            minDiff += 60;
            hrsDiff--;
        }

        System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");

    }

}

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 2017-09-04
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2011-07-29
    • 2018-11-03
    相关资源
    最近更新 更多