跨越时间段改经过时间段
时间: 2024-04-10 11:34:57 浏览: 9
如果你想要计算经过的时间段数量,而不是跨越的时间段数量,我们可以稍作修改。以下是修改后的示例代码:
```java
import java.time.LocalTime;
public class TimePeriods {
public static void main(String[] args) {
LocalTime t1 = LocalTime.of(0, 0); // 00:00
LocalTime t2 = LocalTime.of(3, 0); // 03:00
LocalTime t3 = LocalTime.of(9, 0); // 09:00
LocalTime t4 = LocalTime.of(21, 0); // 21:00
LocalTime t5 = LocalTime.of(24, 0); // 24:00 (midnight)
int count = 0;
LocalTime startTime = LocalTime.of(2, 30); // 02:30
LocalTime endTime = LocalTime.of(1, 30); // 01:30
// Check if the start time is before the end time
if (startTime.isBefore(endTime)) {
if (startTime.isAfter(t1) && startTime.isBefore(t2)) {
count++;
}
if (startTime.isAfter(t2) && startTime.isBefore(t3)) {
count++;
}
if (startTime.isAfter(t3) && startTime.isBefore(t4)) {
count++;
}
if (startTime.isAfter(t4) && startTime.isBefore(t5)) {
count++;
}
if (endTime.isAfter(t1) && endTime.isBefore(t2)) {
count++;
}
if (endTime.isAfter(t2) && endTime.isBefore(t3)) {
count++;
}
if (endTime.isAfter(t3) && endTime.isBefore(t4)) {
count++;
}
if (endTime.isAfter(t4) && endTime.isBefore(t5)) {
count++;
}
} else { // If the start time is after the end time (crosses midnight)
if (startTime.isAfter(t1) || startTime.isBefore(t2)) {
count++;
}
if (startTime.isAfter(t2) || startTime.isBefore(t3)) {
count++;
}
if (startTime.isAfter(t3) || startTime.isBefore(t4)) {
count++;
}
if (startTime.isAfter(t4) || startTime.isBefore(t5)) {
count++;
}
if (endTime.isAfter(t1) || endTime.isBefore(t2)) {
count++;
}
if (endTime.isAfter(t2) || endTime.isBefore(t3)) {
count++;
}
if (endTime.isAfter(t3) || endTime.isBefore(t4)) {
count++;
}
if (endTime.isAfter(t4) || endTime.isBefore(t5)) {
count++;
}
}
System.out.println("The time period passes through " + count + " time segments.");
}
}
```
根据以上代码,计算出2:30~1:30经过了6个时间段。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)