當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java character compareTo()用法及代碼示例

字符類的 compareTo(character another character) 方法用於對兩個對象進行數值比較。

用法

publicintcompareTo(CharcteranotherCharcter )

參數

上述方法隻需要一個參數:

需要比較的字符。

返回

字符類的 compare(char x, char y) 方法返回:

如果給定的 Character 等於參數 Character,則值為 0。

如果給定的 Character 在數值上小於 Character 參數,則該值小於 0

大於給定 Character 的值在數字上大於 Character 參數。

例子1

public class JavaCharacterCompareToExample1 {
public static void main(String[] args) {
    Character firstVal = new Character('g');
Character secondVal = new Character('G');
// compare the first character to the second character.
intcompare1= firstVal.compareTo(secondVal);
if (compare1 == 0) {
System.out.println("The first value 'g' and the second value 'G' are equal.");
 }
else if (compare1>0) {
System.out.println("The first value 'g' is greater than the second value 'G'.");
 }
else {
System.out.println("The first value 'g' is less than the second value'G'.");
          }
     }
}

輸出:

The first value 'g' is greater than the second value 'G'.

例子2

public class JavaCharacterCompareToExample2 {
public static void main(String[] args) {
 Character first = new Character('T');
Character second = new Character('G');
// compare the first character to the second character.
intcompare= first.compareTo(second);
if (compare == 0) {
System.out.println("The first value 'T' and the second value 'G' are equal.");
 }
else if (compare>0) {
System.out.println("The first value 't' is greater than the second value 'G'.");
     }
else {
System.out.println("The first value 'T-' is less than the second value'G'.");
        }
    }
}

輸出:

The first value 't' is greater than the second value 'G'.

例子3

public class JavaCharacterCompareToExample3 {

public static void main(String[] args) {
Character firstVal = new Character('c');
Character secondVal = new Character('a');
  Character thirdVal = new Character('c');

// compare the first character to the second character.
intcompare1=firstVal.compareTo(secondVal);
// compare the first character to the third character.
intcompare2 = firstVal.compareTo(thirdVal);
if (compare1 == 0) {
System.out.println("The first and second values are equal");
       }
else if (compare1>0) {
System.out.println("The first value is greater than the second value");
}
else{
System.out.println("The first value is less than the second value");
        }
if (compare2== 0) {
System.out.println("The first and third values are equal");
 }
else if (compare2 >0) {
System.out.println("The first value is greater than the third value");
      } else {
System.out.println("The first value is less than the third value");
        }
    }

}

輸出:

The first value is greater than the second value
The first and third value are equal



相關用法


注:本文由純淨天空篩選整理自 Java character compareTo() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。