Java 中的 MonthDay compareTo() 方法
可以使用 Java 中 MonthDay 类的 compareTo() 方法比较两个 MonthDay 对象。此方法需要一个参数,即要比较的 MonthDay 对象。
如果第一个 MonthDay 对象大于第二个 MonthDay 对象,它将返回一个正数;如果第一个 MonthDay 对象小于第二个 MonthDay 对象,它将返回一个负数;如果两个 MonthDay 对象相等,它将返回零。
演示此操作的程序如下所述
示例
import java.time.*;
public class Main {
public static void main(String[] args) {
MonthDay md1 = MonthDay.parse("--02-22");
MonthDay md2 = MonthDay.parse("--05-15");
System.out.println("The first MonthDay object is: " + md1);
System.out.println("The second MonthDay object is: " + md2);
int val = md1.compareTo(md2);
if(val > 0)
System.out.println("
The first MonthDay object is greater than the second MonthDay object");
else if(val < 0)
System.out.println("
The first MonthDay object is lesser than the second MonthDay object");
else
System.out.println("
The MonthDay objects are equal");
}
}输出
The first MonthDay object is: --02-22 The second MonthDay object is: --05-15 The first MonthDay object is lesser than the second MonthDay object
现在让我们了解一下上面的程序。
首先显示两个 MonthDay 对象。然后使用 compareTo() 方法比较它们,并使用 if else 语句显示结果。演示此操作的代码段如下
MonthDay md1 = MonthDay.parse("--02-22");
MonthDay md2 = MonthDay.parse("--05-15");
System.out.println("The first MonthDay object is: " + md1);
System.out.println("The second MonthDay object is: " + md2);
int val = md1.compareTo(md2);
if(val > 0)
System.out.println("
The first MonthDay object is greater than the second MonthDay object");
else if(val < 0)
System.out.println("
The first MonthDay object is lesser than the second MonthDay object");
else
System.out.println("
The MonthDay objects are equal");
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP