English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, vamos aprender a converter uma variável do tipo int (int) em um caractere (char) no Java.
Para entender este exemplo, você deve entender o seguinteProgramação JavaTema:
class Main { public static void main(String[] args) { //Create int type variable int num1 = 80; int num2 = 81; //Convert int to char //conversão explícita de tipo char a = (char)num1; char b = (char)num2; //Print the value System.out.println(a); // P System.out.println(b); // Q } }
No exemplo acima, temos a variável do tipo int num1e num2Atenção a esta linha,
char a = (char)num1;
Aqui, usamos a conversão de tipo para converter uma variável do tipo int para uma variável do tipo char. Para obter mais informações, acesseJava Type Conversion.
Por favor, note que esses valores int são considerados valores ASCII. Portanto, obtemosPtem o valor int80e Q tem o valor int 81. Isso é porque P e Q os valores ASCII correspondentes são 80 e 81.
Também podemos usar o método forDigit() da classe Character para converter uma variável do tipo int para char.
class Main { public static void main(String[] args) { //Create int type variable int num1 = 1; int num2 = 13; //Convert int to char //para 0-9os valores entre char a = Character.forDigit(num1, 10); //para 0-9os valores entre char b = Character.forDigit(num2, 16); //Print the value System.out.println(a); // 1 System.out.println(b); // d } }
Atenção à expressão
char a = Character.forDigit(num1, 10);
já usamos o método forDigit(), que converte um valor int para um caractere.
aqui,10e16respectivamente, o valor base em decimal e hexadecimal. Isso é, se o valor int estiver entre9estaremos10como valor base; se o valor int estiver entre15entre eles, usaremos16,等等。
In Java, we can also convert an integer" 0"Add to an integer to convert it to a character. For example,
class Main { public static void main(String[] args) { //Create int type variable int num1 = 1; int num2 = 9; //Convert int to char char a = (char)(num1 + '0'); char b = (char)(num2 + '0'); //Print the value System.out.println(a); // 1 System.out.println(b); // 9 } }
In the above example, please note the following line:
char a = (char)(num1 + '0');
Here, the character" 0"is converted to ASCII value 48. Add the value 48 with num1(that is1)to add. The result is 49 Its ASCII value is1. Therefore, we will add the character '1' as output.
Note: This applies only to int valuesFrom 0 to9.