2016-09-18 52 views
-3

我在因特網上搜索了這個,但無法找到一個精確的解決方案,我發現一個可能的解決方案是讀取整數作爲一個字符串,並使用charAt方法和然後將該字符轉換爲int以打印ascii值。如何在JAVA中打印一個int的ASCII值

但除了上述方法外,還有其他可行的方法嗎?

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

例如,考慮讀整數1,現在我想在屏幕上,這是49

+0

爲什麼不告訴你工作的例子,所以我們有你想要做一個清晰的概念? – shmosel

+2

Java字符是Unicode,它涵蓋比ASCII更多的字符 –

+0

[將字符串轉換爲java中的ASCII數值]可能的副本(http://stackoverflow.com/questions/16458564/convert-string-to-ascii-numeric-value -in-java) –

回答

2

我假設你正在尋找這對要打印的1 ASCII值:

System.out.print((char)a); 
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