Java中的MonthDay compareTo()方法
可以使用compareTo()
Java中MonthDay类中的方法比较两个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("\nThe first MonthDay object is greater than the second MonthDay object"); else if(val < 0) System.out.println("\nThe first MonthDay object is lesser than the second MonthDay object"); else System.out.println("\nThe 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()
方法比较它们,并使用ifelse语句显示结果。演示此代码段如下所示:
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("\nThe first MonthDay object is greater than the second MonthDay object"); else if(val < 0) System.out.println("\nThe first MonthDay object is lesser than the second MonthDay object"); else System.out.println("\nThe MonthDay objects are equal");