我输入了一个数字(0-127),并希望显示带有该索引的ASCII字符。到目前为止,我只用自己的变量实现了这一点。有人可以用输入解释如何做到这一点吗?
我的代码:
import java.util.Scanner;
public class CharCode {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
// obtain index
System.out.print("Enter an ASCII code: ");
String entry = input.next();
// How do I get a char with the inputted ASCII index here?
// I can do it with my own variable, but not with input:
int i = 97;
char c = (char) i; // c is now equal to 'a'
System.out.println(c);
}
}
答案 0 :(得分:2)
我认为你想输入任何ASCII值,它将以char值显示。为此,您需要更改,因为您必须对用户输入执行这些操作。
int entry = input.nextInt(); // get the inputted number as integer
// and
char c = (char) entry;
或强>
对于您当前的实施
//entry has to be String of numbers otherwise it will throw NumberFormatException.
char c = (char) (Integer.parseInt(entry)); // c will contain 'a'