JAVA 需求如下: 1.有设备的日常工作时间段为字符串(HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm) 2.有这个设备工作时间段内还未工作的空闲时间段如字符串(HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm) 3.传入某工序需要的工作时间(分) 3.判断这个设备这天的剩余连续工作时段(如果空闲时段包含了非工作时间,则算做连续的可用时间)是否满足工序的工作时间需要 返回true或false
时间: 2024-02-06 19:04:22 浏览: 57
js将日期格式转换为YYYY-MM-DD HH:MM:SS
这个问题的解决方案和上一个问题类似,只是需要在计算剩余工作时间时,将空闲时间段中的非工作时间也算做连续的可用时间。下面是示例代码:
```java
import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
public class Device {
private ArrayList<Duration> freeTimeSegments = new ArrayList<>();
private ArrayList<Duration> workTimeSegments = new ArrayList<>();
public Device(String workTime, String freeTime) {
String[] workTimeArray = workTime.split(";");
String[] freeTimeArray = freeTime.split(";");
for (String segment : workTimeArray) {
String[] times = segment.split("-");
LocalTime start = LocalTime.parse(times[0]);
LocalTime end = LocalTime.parse(times[1]);
workTimeSegments.add(Duration.between(start, end));
}
for (String segment : freeTimeArray) {
String[] times = segment.split("-");
LocalTime start = LocalTime.parse(times[0]);
LocalTime end = LocalTime.parse(times[1]);
freeTimeSegments.add(Duration.between(start, end));
}
}
public boolean hasEnoughTime(Duration duration) {
Duration remainingTime = Duration.ZERO;
boolean isWorking = false;
for (Duration segment : workTimeSegments) {
if (!isWorking && !freeTimeSegments.isEmpty()) {
Duration freeSegment = freeTimeSegments.remove(0);
if (freeSegment.compareTo(segment) <= 0) {
segment = segment.minus(freeSegment);
} else {
freeSegment = segment;
segment = Duration.ZERO;
}
remainingTime = remainingTime.plus(freeSegment);
}
if (remainingTime.compareTo(Duration.ZERO) <= 0) {
remainingTime = segment;
isWorking = true;
} else {
remainingTime = remainingTime.plus(segment);
}
for (Duration freeSegment : freeTimeSegments) {
if (!isWorking) {
if (freeSegment.compareTo(segment) <= 0) {
segment = segment.minus(freeSegment);
} else {
freeSegment = segment;
segment = Duration.ZERO;
}
remainingTime = remainingTime.plus(freeSegment);
} else {
if (remainingTime.compareTo(duration) >= 0) {
return true;
}
if (freeSegment.compareTo(remainingTime) >= 0) {
remainingTime = remainingTime.plus(freeSegment.minus(remainingTime));
} else {
remainingTime = remainingTime.minus(freeSegment);
}
}
}
}
return false;
}
public static void main(String[] args) {
Device device = new Device("09:00-10:00;13:00-14:00", "09:58-10:00;11:00-12:00;13:00-13:03");
Duration duration = Duration.ofMinutes(5);
boolean result = device.hasEnoughTime(duration);
System.out.println(result); // should print "true"
}
}
```
注意到这个示例代码中,在遍历工作时间段之前,我们先判断是否有空闲时间段包含了非工作时间,如果有,则在第一个工作时间段中减去这段非工作时间。在遍历空闲时间段时,如果当前是工作时间段,我们按照上一个问题的方法来计算剩余时间;如果当前是非工作时间段,我们先判断是否在工作时间段内,如果在,则将这段时间加到剩余时间中,否则忽略这段时间。
阅读全文