可以使用isNegative()Java中Duration类中的方法来检查持续时间是否为负。此方法不需要任何参数。此外,如果持续时间为负数,则返回true,否则返回false。
演示此的程序如下所示-
import java.time.Duration;
public class Demo {
public static void main(String[] args) {
Duration d = Duration.ofSeconds(5);
boolean flag = d.isNegative();
System.out.println("The duration is: " + d);
if(flag)
System.out.println("The above duration is negative");
else
System.out.println("The above duration is not negative");
}
}输出结果
The duration is: PT5S The above duration is not negative
现在让我们了解上面的程序。
首先,显示持续时间。然后该标志保存isNegative()方法的返回值。根据标志中的值,持续时间为负数或不为负数,并进行打印。演示这的代码片段如下-
Duration d = Duration.ofSeconds(5);
boolean flag = d.isNegative();
System.out.println("The duration is: " + d);
if(flag)
System.out.println("The above duration is negative");
else
System.out.println("The above duration is not negative");