1

我有一个数字(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);
    }
}
4

1 回答 1

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'
于 2013-01-29T01:54:14.963 回答