如何在Java中获取ASCII代码的值?

时间:2016-09-28 19:34:38

标签: java ascii

我试图从一串值中返回一个值数组。但是,我的代码返回已输入的字符串的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,51,49,52,49,53,57,50]

3 个答案:

答案 0 :(得分:4)

这是另一种方式:

只需用' 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,3,1,4,1,5,9,2]

答案 1 :(得分: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;
    }
}

答案 2 :(得分:-2)

使用Integer.parseInt和Character.toString作为@NeilLocketz提到。您的数组A是一个int数组,因此您需要获取正在阅读的字符的基础整数

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