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


Java Character compare()用法及代碼示例

Character 類的 compare(char x, char y) 方法用於對兩個 char 值進行數值比較。返回的最終值類似於以下返回的值:

Character.valueoOf(x).compareTo(Character.valueOf(y))

用法

public static intcompare(char x, char y)

參數

上述方法需要兩個參數:

  • char x 這是要比較的第一個字符
  • char y 這是要比較的第二個字符

返回值

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

  • 如果 x==y,則值為 0
  • 如果 x<y,則值小於 0。
  • 如果 x>y,則值大於 0。

例子1

public class JavaCharacterCompareExample1 {
public static void main(String[] args) {
char firstValue = 'A';
char secondValue = 'B';
// compare the first char to the second
    int compareOneTwo = Character.compare(firstValue, secondValue);
    if (compareOneTwo> 0) {
    System.out.println("First value is greater than second value");
    }
    else {
System.err.println("First value is less than second value.");
    }
   }
}

輸出:

First value is less than the second value.

例子2

public class JavaCharacterCompareExample2{
    public static void main(String[] args) {
char firstValue = '1';
char secondValue = '2';
// compare the first char to the second
    int comp = Character.compare(firstValue, secondValue);
    if (comp< 0) {
    System.err.println("Value 1 is greater than the value 2.");
    }
    else {
    System.err.println("Value 1 is less than the second value2.");
        }
      }
}

輸出:

Value 1 is greater than the value 2.

例子3

public class JavaCharacterCompareExample3 {
public static void main(String[] args) {
    char firstVal = 'J';
    char secondVal ='J';
    char thirdVal = 'M';
// compare the first char to the second CHAR
int compareOneTwo = Character.compare(firstVal, secondVal);
// compare the first char to the third
int compareOneThree = Character.compare(firstVal, thirdVal);
if (compareOneTwo == 0) {
    System.out.println("First and second values are equal.");
    } else if (compareOneTwo> 0) {
    System.out.println("First value is greater than the second value.");
    } else {
    System.out.println("First value is less than the second value.");
    }
    if (compareOneThree == 0) {
    System.out.println("First and third value are equal.");
    }
else if (compareOneTwo> 0) {
    System.out.println("First value is greater than the third value.");
    }
else {
    System.out.println("First value is less than the third value.");
       }

    }
}

輸出:

First and second values are equal.
First value is less than the third value.



相關用法


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