如何在JAVA中打印int的ASCII值

时间:2016-09-18 09:49:19

标签: java int ascii

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

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

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

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

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找这个:

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

答案 1 :(得分:1)

这样做的简单方法是:

<小时/> 对于整个字符串

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]);
      }
    }
}

<小时/> 对于单个角色: String number="123"; asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value