我正在做一个练习,我需要根据时区的不同来计算小时,所以我基本上想出了以下代码:
System.out.print("What is the time difference, in hours, between your home and your destination? ");
Scanner input = new Scanner(System.in);
int hoursDif = input.nextInt();
input.nextLine();
int mid;
if (hoursDif < 0){
mid = 24 + hoursDif;
}
else{
mid = hoursDif;
}
int noon;
if (hoursDif+12 < 24){
noon = hoursDif + 12;
}
else{
noon = hoursDif + 12 +- 24;
}
System.out.print("That means that when it is midnight at home it will be " + mid + ":00 and noon: " + noon);
但是问题是,该课程才刚刚开始,还没有看到循环,所以有人知道是否有一种方法可以获取相同的输出,但是没有if语句吗?
答案 0 :(得分:0)
使用适当的LocalDateTime
对象,这非常简单。
System.out.print("What is the time difference, in hours, between your home and your destination? ");
Scanner input = new Scanner(System.in);
int hoursDif = input.nextInt();
LocalDateTime localDateTime = LocalDateTime.now();
int mid = localDateTime.truncatedTo(ChronoUnit.DAYS).plusHours(hoursDif).getHour();
int noon = localDateTime.truncatedTo(ChronoUnit.DAYS).plusHours(12).plusHours(hoursDif).getHour();
System.out.print("That means that when it is midnight at home it will be " + mid + ":00 and noon: " + noon);
您仅获得当前时间,将其截断为DAYS(因此为00:00:00),然后添加您输入的时间。