2010-10-05 25 views
0

我需要Java代碼。請幫幫我。例如:當我在ASCII輸入號碼如何以我輸入的ASCII碼顯示所需的值?

0 the output will be nul 
1 for soh 
2 for stx until it reaches the max number of ASCII. 

考慮以下代碼。它輸出一個ASCII碼。我怎樣才能扭轉它?

String test = "ABCD"; 
for (int i = 0; i < test.length(); ++i) { 
    char c = test.charAt(i); 
    int j = (int) c; 
    System.out.println(j); 
} 
+1

缺少的功課標籤 – Ishtar 2010-10-05 13:11:29

回答

1
import java.io.*; 
import java.lang.*; 
    public class CharToASCII{ 
     public static void main(String args[]) throws IOException{ 
      BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println("Enter the char:"); 
      String str = buff.readLine(); 
      for (int i = 0; i < str.length(); ++i){ 
      char c = str.charAt(i); 
      int j = (int) c;// your work is done here 
      System.out.println("ASCII OF "+c +" = " + j + "."); 
      } 
     } 
     } 
+0

我複製你的編,但它有4個錯誤 – jhoanne 2010-10-05 13:13:36

+0

@jhoanne你需要進行適當的進口 – 2010-10-05 13:15:55

+0

@jhoanne更新了代碼 – 2010-10-05 13:17:45

1

只投一個整數值,如果您需要低於「0」的ASCII值一些文本輸出到char:

int value = (int) 'a'; 
System.out.println((char) value); // prints a 

,你需要從整數值的映射(ASCII碼數)字面,像這樣:

String[] literals0to32 = {"NUL", "SOH", "STX", /* to be continued */ }; 

private static String toLiteral(int value) { 

    if (value < 0 || value > 255) 
     throw new IKnowThatIHaveToValidateParametersException(); 

    if (value < 32) 
    return literals0To32[value]; 
    else 
    return (char) value; 
} 
+0

感謝,但是怎麼樣時,我的教授。輸入數字0它將打印nul。? – jhoanne 2010-10-05 13:05:17

+0

不,在這種情況下,它會打印一些未定義的內容。編輯我的答案,爲ASCII – 2010-10-05 13:07:26

+0

快速解決方案(片段),你可以再次編輯所有的代碼開始在公共課。請。 – jhoanne 2010-10-05 13:43:44

-1
class prg1{ 
    public static void main(char a){ 
     int b=(int)a; 
     System.out.println("ASCII value ="+b); 
    } 
} 
-1

試試這個:

public static void main(String[] args) { 
    String a = "a"; 
    char b = a.charAt(0); 
    int c = b; 
    System.out.println(c); 
} 
相關問題