2016-09-28 67 views
0

我想從一串值中返回一個數組值。但是,我的代碼返回已輸入字符串的ASCII碼值。這是我的代碼,一個測試用例,以及它當前返回的內容。如何獲得Java中的ASCII碼值?

public static int[] stringToBigInt(String s) { 
    int []A = new int [SIZE]; 

    int j = s.length() - 1; 
    for (int i = A.length - 1; j >= 0 && i >= 0; --i){ 
     A[i] = s.charAt(j); 
     --j; 
    } 

    return A; 
} 

    System.out.println("Test 8: Should be\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 4, 1, 5, 9, 2]"); 
    System.out.println(Arrays.toString(stringToBigInt("3141592"))); 
    System.out.println(); 

執行命令 [0,0,0,0,0,0,0,0,0,0,0,0,0,51,49,52,49,53,57,50 ]

+0

看一看一個ASCII表:' '3''被'51','' 1''是' 49'等...... –

+2

'int'不是'char'。把你的字符放在char []中,而不是int [] – njzk2

+1

注意:'int a []'是聲明數組的Java方法。 – Maroun

回答

3

這裏的另一種方式:

就用 '0' 字符減去字符。

public static int[] stringToBigInt(String s) { 
     int []A = new int [SIZE]; 

     int j = s.length() - 1; 
     for (int i = A.length - 1; j >= 0 && i >= 0; --i){ 
      A[i] = s.charAt(j) - '0'; 
      --j; 
     } 

     return A; 
    } 

輸出是:

[0,0,0,0,0,0,0,0,0,0,0,0,0,3,1,4,1 ,5,9,2]

+0

非常有創意! –

+0

@RobertColumbia Thx! –

0

使用Integer.parseInt和Character.toString as @NeilLocketz提到。您的數組Aint的一個數組,因此您需要獲取正在閱讀的字符的基礎整數

for (int i = A.length - 1; j >= 0 && i >= 0; --i){ 
    A[i] = Integer.parseInt(Character.toString(s.charAt(j))); 
    --j; 
} 
+0

這個答案有什麼問題? –

0

下面是工作代碼:

public class Test { 
    private static final int SIZE = 20; 

    public static void main(final String[] args) { 
     System.out.println("Test 8: Should be\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 4, 1, 5, 9, 2]"); 
     System.out.println(Arrays.toString(stringToBigInt("3141592"))); 
     System.out.println(); 
    } 

    public static int[] stringToBigInt(final String s) { 
     int[] A = new int[SIZE]; 

     int j = s.length() - 1; 
     for(int i = A.length - 1; j >= 0 && i >= 0; --i) { 
      A[i] = Character.getNumericValue(s.charAt(j)); 
      --j; 
     } 

     return A; 
    } 
}