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