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


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