如何在JAVA中打印int的ASCII值

问题描述 投票:-4回答:2

我在互联网上搜索过这个但是无法找到精确的解决方案,我发现一个可能的解决方案是将整数读作字符串,并使用charAt方法然后将字符转换为int以打印ascii值。

但除了上述方法之外,还有其他可能的方法吗?

int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.

例如,将读取整数视为1,现在我希望将ASCII值1打印在屏幕上,即49

java int ascii
2个回答
2
投票

我假设你正在寻找这个:

System.out.print((char)a);

1
投票

这样做的简单方法是:


For the Whole String
public class ConvertToAscii{
    public static void main(String args[]){
      String number = "1234";
      int []arr = new int[number.length()];
      System.out.println("THe asscii value of each character is: ");
      for(int i=0;i<arr.length;i++){
          arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
          System.out.print(" "+arr[i]);
      }
    }
}


For the single Character: String number="123"; asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value
© www.soinside.com 2019 - 2024. All rights reserved.