当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。