我正在尝试编写一个程序,在该程序中,控制台会以“军事时间”或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设置为2,将时间1700设置为2,则可以给我正确的9个小时。但是,如果相差10个小时或更长时间,则将花费1个小时零花很多时间。我以为使用String.format方法会有所帮助,但它不会做任何事情。

第二:我不确定如何处理时间1比时间2晚的情况。

谢谢!

最佳答案

您可以尝试下面的代码,这些代码将以军事格式给出时差:

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

    }

}

关于java - 如何获得军事时差以正确阅读?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39313516/

10-11 16:25