如何使用强制转换运算符
How to use cast operator
我目前正在处理作业中的一个问题。问题是:
"Write a program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, ..., and Z for 35. (Hint: Use the cast operator, static_cast() for numbers >= 10."
我不知道如何使用强制转换运算符,我需要一些指导。
这是我的代码:
import java.util.Scanner;
public class Question_4 {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int integer = 0;
System.out.println("Enter a number between 0 - 35: ");
integer = sc.nextInt();
if(integer <= 9){
System.out.println("Number entered is " + integer);
}
else{
System.out.println(static_cast.class<char>('A' + (integer -
10)););
}
}//END Main
}
你可以这样做:
System.out.println((char)((byte)'A' + (integer - 10)) );
(byte)'A'
将给出 'A' char (97) 的字节表示
(char)
将数字转换回字符
我目前正在处理作业中的一个问题。问题是:
"Write a program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, ..., and Z for 35. (Hint: Use the cast operator, static_cast() for numbers >= 10."
我不知道如何使用强制转换运算符,我需要一些指导。
这是我的代码:
import java.util.Scanner;
public class Question_4 {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int integer = 0;
System.out.println("Enter a number between 0 - 35: ");
integer = sc.nextInt();
if(integer <= 9){
System.out.println("Number entered is " + integer);
}
else{
System.out.println(static_cast.class<char>('A' + (integer -
10)););
}
}//END Main
}
你可以这样做:
System.out.println((char)((byte)'A' + (integer - 10)) );
(byte)'A'
将给出 'A' char (97) 的字节表示
(char)
将数字转换回字符