首页 > 解决方案 > 将用户输入的整数转换为具有该 ASCII 码的字符

问题描述

这是我的第一篇文章。我也刚开始。我们应该使用方法调用从用户那里获取一个整数,然后使用另一个方法中输入的值并将其转换为 ASCII 字符。这就是我所拥有的——

public static void main(String[] args) {
    System.out.println(
            "*** You will enter values in the range of 33-126 for the whole numbers and 33.0-126.0 for the real numbers***");

    System.out.println("");

    System.out.println("The number is " + getWholeNumber() + 
                       " and the character for this is a(n) " + printCharacter());
}

public static int getWholeNumber() {
    int getWholeNumber;
    System.out.println("Enter a whole number, one that does not have a decimal point: ");
    Scanner input = new Scanner(System.in);
    getWholeNumber = input.nextInt();
    return getWholeNumber;
}

public static void printCharacter(int getWholeNumber) {
    char letter = (char) getWholeNumber();
    System.out.println(letter);
}

我已成功调用该方法并显示了整数,但似乎无法弄清楚如何将其转换为数字表示的 ASCII 字符。

标签: java

解决方案


如果您首先将 int 转换为 char,您将拥有您的 ascii 代码。

例如:

int iAsciiValue = 9; // Currently just the number 9, but we want 
 //Tab character
// Put the tab character into a string
String strAsciiTab = Character.toString((char) iAsciiValue);

推荐阅读