Java Character compareTo()方法

java.lang.Character.compareTo(Character anotherCharacter) 比较两个字符的对象的数字。

1 语法

public int compareTo(Character anotherCharacter)

2 参数

anotherCharacter:进行比较字符

3 返回值

此方法返回值0,如果该参数字符等于这个字符;返回值小于0,如果这个字符在数值上比Character参数少;返回一个大于0的值,如果这个字符在数值上比Character参数(无符号比较)。这是严格意义上的数值比较;它不依赖语言环境的。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Character compareTo()方法
 */
import java.lang.*;

public class CharacterDemo {

   public static void main(String[] args) {

      // create 2 Character objects c1, c2
      Character c1, c2;

      // assign values to c1, c2
      c1 = new Character('a');
      c2 = new Character('b');

      // create an int type
      int res;

      // compare c1 with c2 and assign result to res
      res = c1.compareTo(c2);

      String str1 = "Both values are equal ";
      String str2 = "First character is numerically greater";
      String str3 = "Second character is numerically greater";

      if( res == 0 ){
      	 System.out.println( str1 );
      }
      else if( res > 0 ){
      	 System.out.println( str2 );
      }
      else if( res < 0 ){
      	 System.out.println( str3 );
      }
   }
}

输出结果为:

Second character is numerically greater

 

热门文章

优秀文章