Skip to content

Latest commit

 

History

History
79 lines (57 loc) · 2.99 KB

File metadata and controls

79 lines (57 loc) · 2.99 KB

Java 程序:charint的转换

原文: https://beginnersbook.com/2019/04/java-char-to-int-conversion/

在本教程中,我们将看到如何借助示例将char转换为int。将字符转换为整数等同于查找给定字符的 ASCII 值(这是一个整数)。

charint隐式类型转换

由于char是与int相比较小的数据类型,因此我们不需要在此处进行显式类型转换。将char值简单赋值给int变量就可以了,编译器会自动将char转换为int,这个过程称为隐式类型转换或类型提升。

在下面的示例中,我们将char值分配给整数变量,而不进行任何类型转换。编译器在这里自动进行转换,这仅适用于我们将较小的数据类型分配给较大的数据类型,否则我们必须进行显式类型转换。

public class JavaExample{  
   public static void main(String args[]){  
	char ch = 'A';
	char ch2 = 'Z';
	int num = ch;
	int num2 = ch2;
	System.out.println("ASCII value of char "+ch+ " is: "+num);
	System.out.println("ASCII value of char "+ch2+ " is: "+num2);
   }
}

输出:

Java char to int conversion example

使用Character.getNumericValue()char转换为int

我们还可以使用Character.getNumericValue(char ch)方法将char转换为int。此方法接受char作为参数,并在转换后返回等效的int(ASCII)值。

这里我们有两个char变量chch2,我们使用Character.getNumericValue()方法将它们转换为整数numnum2

public class JavaExample{  
   public static void main(String args[]){  
	char ch = 'P';
	char ch2 = 'h';

	//conversion using Character.getNumericValue()
	int num = Character.getNumericValue(ch);
	int num2 = Character.getNumericValue(ch2);
	System.out.println("ASCII value of char "+ch+ " is: "+num);
	System.out.println("ASCII value of char "+ch2+ " is: "+num2);
   }
}

输出:

Java convert char to int example

使用Integer.parseInt()方法将char转换为int

这里我们使用Integer.parseInt(String)方法将给定的char转换为int。由于此方法接受字符串参数,因此我们使用String.valueOf()方法将char转换为String,然后将转换后的值传递给方法。

public class JavaExample{  
   public static void main(String args[]){  
	char ch = '9';

	/* Since parseInt() method of Integer class accepts
   	 * String argument only, we must need to convert
	 * the char to String first using the String.valueOf()
	 * method and then we pass the String to the parseInt()
	 * method to convert the char to int
	 */
	int num = Integer.parseInt(String.valueOf(ch));

	System.out.println(num);
   }
}

输出:

Java char to int conversion example