Java 爪哇军事时间的时差

Java 爪哇军事时间的时差,java,time,Java,Time,因此,对于一项任务,我们必须编写一个程序,用两次军事时间显示它们之间的小时和分钟差异,假设第一次是两次中较早的一次。我们不允许使用if语句,因为它在技术上还没有被学习。下面是一个运行时的示例。在引号中,我将在提示输入时输入手动输入的内容 java MilitaryTime Please enter first time: "0900" Please enter second time: "1730" 8 hours 30 minutes (this is the final an

因此,对于一项任务,我们必须编写一个程序,用两次军事时间显示它们之间的小时和分钟差异,假设第一次是两次中较早的一次。我们不允许使用if语句,因为它在技术上还没有被学习。下面是一个运行时的示例。在引号中,我将在提示输入时输入手动输入的内容

java MilitaryTime

Please enter first time:  "0900"

Please enter second time:  "1730"

8 hours 30 minutes    (this is the final answer)
我可以很容易地用以下代码完成这部分:

class MilitaryTime  {

   public static void main(String [] args) {

      Scanner in = new Scanner(System.in);

            System.out.println("Please enter the first time: ");

            int FirstTime = in.nextInt();

            System.out.println("Please enter the second time: ");

            int SecondTime = in.nextInt();

            int FirstHour = FirstTime / 100;

            int FirstMinute = FirstTime % 100;

            int SecondHour = SecondTime / 100;

            int SecondMinute = SecondTime % 100;

            System.out.println( ( SecondHour - FirstHour ) + " hours " + ( SecondMinute 

                - FirstMinute ) + " minutes "  );
       }
}
现在我的问题是有些东西没有分配(或者我不会在这里!)书中这个问题还有另一个部分说,拿我们刚刚编写的程序,处理第一次比第二次晚的情况。这真的让我很好奇如何做到这一点,也让我很困惑。同样,我们不允许使用if语句,或者这很容易,因为我们基本上拥有所有的数学函数


例如,第一次是1730,第二次是0900,因此现在返回15小时30分钟。

我将执行以下操作:

System.out.println(Math.abs( SecondHour - FirstHour ) + " hours " + Math.abs( SecondMinute - FirstMinute ) + " minutes "  );

绝对值将给出两倍之间的差作为正整数。

您可以这样做

//Code like you already have
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();

//Now we can continue using the code you already wrote by
//forcing the smaller of the two times into the 'firstTime' variable.
//This forces the problem to be the same situation as you had to start with
if (secondTime < firstTime) {
    int temp = firstTime;
    firstTime = secondTime;
    secondTime = temp;
}

//Continue what you already wrote
//像您已有的那样编写代码
System.out.println(“请输入第一次:”);
int firstTime=in.nextInt();
System.out.println(“请输入第二次:”);
int secondTime=in.nextInt();
//现在我们可以继续使用您已经编写的代码
//将两次中较小的一次强制输入“firstTime”变量。
//这迫使问题与您必须开始的情况相同
如果(第二次<第一次){
int temp=第一次;
第一次=第二次;
第二时间=温度;
}
//继续你已经写的

还有很多其他的方法,但这是我在学习时用来解决类似问题的方法。另外,请注意,我更改了变量名以遵循java命名约定-变量的大小写较低。

我建议使用。有很多日期和时间函数

例如:

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = format.parse("10-05-2013 09:00");
Date endDate = format.parse("11-05-2013 17:30");

DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);

int years = Years.yearsBetween(jdStartDate, jdEndDate).getYears();
int days = Days.daysBetween(jdStartDate, jdEndDate).getDays();
int months =  Months.monthsBetween(jdStartDate, jdEndDate).getMonths();
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();

System.out.println(hours + " hours " + minutes + " minutes");
您的预期计划如下:

SimpleDateFormat format = new SimpleDateFormat("hhmm");
Dates tartDate = format.parse("0900");
Date endDate = format.parse("1730");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
minutes = minutes % 60;

System.out.println(hours + " hours " + minutes + " minutes");
输出:

8 hours 30 minutes

通常,在处理这种性质的时间计算时,我会使用Joda time,但假设您不关心日期组件,也不跨越日期边界,您可以简单地将值转换为午夜后的分或秒

基本上你的问题是一个简单的事实,一小时有60分钟,这使得做简单的数学不可能,你需要一些更普遍的东西

例如,
0130
实际上是从午夜开始的90分钟,
1730
是从午夜开始的1050分钟,因此相差16小时。您可以简单地减去这两个值以得到差值,然后将其转换回小时和分钟…例如

public class MilTimeDif {

    public static void main(String[] args) {
        int startTime = 130;
        int endTime = 1730;
        int startMinutes = minutesSinceMidnight(startTime);
        int endMinutes = minutesSinceMidnight(endTime);

        System.out.println(startTime + " (" + startMinutes + ")");
        System.out.println(endTime + " (" + endMinutes + ")");

        int dif = endMinutes - startMinutes;

        int hour = dif / 60;
        int min = dif % 60;

        System.out.println(hour + ":" + min);

    }

    public static int minutesSinceMidnight(int milTime) {
        double time = milTime / 100d;

        int hours = (int) Math.floor(time);
        int minutes = milTime % 100;

        System.out.println(hours + ":" + minutes);

        return (hours * 60) + minutes;
    }

}
一旦开始包含日期组件或滚动日期边界,获取Joda timeout

import java.util.Scanner;
import java.util.Scanner;

 public class TimeDifference{

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    // read first time
    System.out.println("Please enter the first time: ");
    int firstTime = in.nextInt();

    // read second time
    System.out.println("Please enter the second time: ");
    int secondTime = in.nextInt();

    in.close();

    // if first time is more than second time, then the second time is in
    // the next day ( + 24 hours)
    if (firstTime > secondTime)
        secondTime += 2400;

    // first hour & first minutes
    int firstHour = firstTime / 100;
    int firstMinute = firstTime % 100;

    // second hour & second minutes
    int secondHour = secondTime / 100;
    int secondMinute = secondTime % 100;

    // time difference
    int hourDiff = secondHour - firstHour;
    int minutesDiff = secondMinute - firstMinute;

    // adjust negative minutes
    if (minutesDiff < 0) {
        minutesDiff += 60;
        hourDiff--;
    }

    // print out the result
    System.out.println(hourDiff + " hours " + minutesDiff + " minutes ");

 }
}
公共课时差{ 公共静态void main(字符串[]args){ 扫描仪输入=新扫描仪(系统输入); //第一次阅读 System.out.println(“请输入第一次:”); int firstTime=in.nextInt(); //再读一遍 System.out.println(“请输入第二次:”); int secondTime=in.nextInt(); in.close(); //如果第一次超过第二次,则第二次在 //第二天(+24小时) 如果(第一次>第二次) 第二次+=2400; //第一小时和第一分钟 int firstHour=firstTime/100; int firstMinute=firstTime%100; //第二小时和第二分钟 int secondHour=secondTime/100; int second minute=secondTime%100; //时差 int hourDiff=第二小时-第一小时; int minutesDiff=第二分钟-第一分钟; //调整负分钟数 如果(分钟差<0){ 分钟差+=60; 霍尔迪夫; } //把结果打印出来 系统输出打印项数(小时数+小时数+分钟数+分钟数); } }
此操作不使用ifs和日期。您只需要使用整数除法“/”、整数余数“%”、绝对值和celing。也许可以简化,但我现在太懒了。我挣扎了几个小时才弄明白,似乎没有其他人不使用更高级的功能就得到了答案。这个问题出现在Cay Horstmann的Java书中。《Java概念》一书的Java5-6版本中的第4章

import java.util.Scanner;
公开课军事时间{
公共静态void main(字符串[]args){
//创建输入对象
扫描仪输入=新扫描仪(系统输入);
System.out.println(“输入时间A:”);
字符串timeA=in.next();
System.out.println(“输入时间B:”);
字符串timeB=in.next();
//获取时间的小时和分钟a
intahours=Integer.parseInt(timeA.substring(0,2));
int-aMinutes=Integer.parseInt(timeA.substring(2,4));
//获取timeB的小时和分钟数
intbhours=Integer.parseInt(timeB.substring(0,2));
int-bMinutes=Integer.parseInt(timeB.substring(2,4));
//计算每次的总分钟数
int原子分钟=小时*60+分钟;
int b总分钟=b小时*60+b分钟;
//timeA>timeB:solution=(1440分钟-(原子分钟-b总分钟))
//timeAtimeeB…我们使用mod和mod余数
//如果timeA>timeB,则判定为1,如果相反,则判定为0。
整数决策器=((原子分钟-B总分钟+1440)/1440);
//当时间相等时使用4个特例。这样我们得到0
//相等时的时间差项,否则为1。
int equalsDecider=(int)Math.abs((原子分钟-b总分钟));
//fullDayMaker用于在timeA>timeB时添加1440术语
import java.util.*;

class Time
{
    static Scanner in=new Scanner(System.in);
    public static void main(String[] args)
    {
        int time1,time2,totalTime;
        System.out.println("Enter the first time in military:");
        time1=in.nextInt();
        System.out.println("Enter the second time in military:");
        time2=in.nextInt();
        totalTime=time2-time1;
        String temp=Integer.toString(totalTime);
        char hour=temp.charAt(0);
        String min=temp.substring(1,3);
        System.out.println(hour+" hours "+min+" minutes");
    }
}
import java.util.Scanner;

public class MilitaryTime {

    public static void main (String[] args){

        //creates input object
        Scanner in = new Scanner(System.in);

        System.out.println("Enter time A: ");
        String timeA = in.next();

        System.out.println("Enter time B: ");
        String timeB = in.next();

        //Gets the hours and minutes of timeA
        int aHours = Integer.parseInt(timeA.substring(0,2));
        int aMinutes = Integer.parseInt(timeA.substring(2,4));

        //Gets the hours and minutes of timeB
        int bHours = Integer.parseInt(timeB.substring(0,2));
        int bMinutes = Integer.parseInt(timeB.substring(2,4));

        //calculates total minutes for each time
        int aTotalMinutes = aHours * 60 + aMinutes;
        int bTotalMinutes = bHours * 60 + bMinutes;


       //timeA>timeB: solution = (1440minutes - (aTotalMinutes - bTotalMinutes))
       //timeA<timeB: solution is (bTotalMinutes - aTotalMinutes) or   
       //-(aTotalMinutes - bTotalMinutes)
       //we need 1440 term when  timea>timeeB... we use mod and mod remainder

        //decider is 1 if timeA>timeB and 0 if opposite.
        int decider = ((aTotalMinutes - bTotalMinutes +1440)/1440);
        // used 4 Special case when times are equal. this way we get 0
        // timeDiffference term when equal and 1 otherwise.

        int equalsDecider = (int) Math.abs((aTotalMinutes - bTotalMinutes));

        //fullDayMaker is used to add the 1440 term when timeA>timeB
        int fullDayMaker = 1440 * decider;
        int timeDifference = (equalsDecider)* (fullDayMaker - (aTotalMinutes - bTotalMinutes));

        // I convert back to hours and minmutes using modulater
        System.out.println(timeDifference/60+" hours and "+timeDifference%60+" minutes");
    }
}
String inputStart = "0900";
String inputStop = "1730";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HHmm" );;

LocalTime start = formatter.parse ( inputStart , LocalTime :: from );
LocalTime stop = formatter.parse ( inputStop , LocalTime :: from );

Duration duration = Duration.between ( start , stop );
System.out.println ( "From start: " + start + " to stop: " + stop + " = " + duration );
    public class MilitaryTime {
    /**
     * MilitaryTime A time has a certain number of minutes passed at 
     *              certain time of day.
     * @param milTime The time in military format
    */
    public MilitaryTime(String milTime){
        int hours = Integer.parseInt(milTime.substring(0,2));
        int minutes = Integer.parseInt(milTime.substring(2,4));
        timeTotalMinutes = hours * 60 + minutes;

    }
    /**
     * Gets total minutes of a Military Time
     * @return gets total minutes in day at certain time
     */
    public int getMinutes(){
        return timeTotalMinutes;
    }

    private int timeTotalMinutes;   
    }
 public class TimeInterval {

/**
  A Time Interval is amount of time that has passed between two times
  @param timeA first time
  @param timeB second time
*/
public TimeInterval(MilitaryTime timeA, MilitaryTime timeB){

    // A will be shorthand for timeA and B for timeB
    // Notice if A<B timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B)
    // Notice if A>B timeDifferential = - (A - B)
    // Both will use timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B),
    //  but we need to make TOTAL_MINUTES_IN_DAY dissapear when needed


    //Notice A<B following term "x" is 1 and if A>B then it is 0.
    int x = (timeA.getMinutes()-timeB.getMinutes()+TOTAL_MINUTES_IN_DAY)
             /TOTAL_MINUTES_IN_DAY;
    // Notice if A<B then  term "y" is TOTAL_MINUTES_IN_DAY(1440 min) 
    // and if A<B it is 0
    int y = TOTAL_MINUTES_IN_DAY * x;
    //yay our TOTAL_MINUTES_IN_DAY dissapears when needed.

    int timeDifferential = y - (timeA.getMinutes() - timeB.getMinutes());
    hours = timeDifferential / 60;
    minutes = timeDifferential % 60;

    //Notice that if both hours are equal, 24 hours will be shown.
    //  I assumed that we would knoe if something start at same time it
    //   would be "0" hours passed

}
/**
 * Gets hours passed between 2 times
 * @return hours of time difference 
 */
public int getHours(){
    return hours;
}

/**
 * Gets minutes passed after hours accounted for
 * @return minutes remainder left after hours accounted for
 */ 
public int getMinutes(){
    return minutes;
}

private int hours;
private int minutes;
public static final int TOTAL_MINUTES_IN_DAY = 1440;//60minutes in 24 hours

}
import java.util.Scanner;

public class MilitaryTimeTester {
    public static void main (String[] args){

        Scanner in = new Scanner(System.in);

        System.out.println("Enter time A: ");
        MilitaryTime timeA = new MilitaryTime(in.nextLine());

        System.out.println("Enter time B: ");
        MilitaryTime timeB = new MilitaryTime(in.nextLine());

        TimeInterval intFromA2B = new TimeInterval(timeA,timeB);

        System.out.println("Its been "+intFromA2B.getHours()+" hours and "+intFromA2B.getMinutes()+" minutes.");   
    }
}