【问题标题】:How to print ASCII value of an int in JAVA如何在 JAVA 中打印 int 的 ASCII 值
【发布时间】:2017-01-26 03:32:23
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您为什么不展示一个工作示例,以便我们更清楚地了解您要做什么?
  • Java 字符是 Unicode,它比 ASCII 包含更多的字符
  • 如果a 最终成为123 或-456 怎么办?

标签: java int ascii


【解决方案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

【讨论】:

    【解决方案2】:

    我假设你正在寻找这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2022-12-10
      • 2014-04-11
      • 2019-10-05
      • 2017-11-06
      • 1970-01-01
      相关资源
      最近更新 更多