2

好的,我将在这里尝试解释我的问题,我需要做的是将字符串数组转换为 int 数组。

这是我所拥有的一部分(以及初始设置)

   System.out.println("Please enter a 4 digit number to be converted to decimal ");
    basenumber = input.next();

    temp = basenumber.split("");
    for(int i = 0; i < temp.length; i++)
        System.out.println(temp[i]);

    //int[] numValue = new int[temp.length];
    ArrayList<Integer>numValue = new ArrayList<Integer>();

    for(int i = 0; i < temp.length; i++)
        if (temp[i].equals('0')) 
            numValue.add(0);
        else if (temp[i].equals('1')) 
            numValue.add(1);
                     ........
        else if (temp[i].equals('a') || temp[i].equals('A'))
            numValue.add(10);
                     .........
             for(int i = 0; i < numValue.size(); i++)
        System.out.print(numValue.get(i));

基本上我正在尝试将 0-9 设置为实际数字,然后从输入字符串(例如 Z3A7)中继续将 az 设置为 10-35,理想情况下将打印为 35 3 10 7

4

3 回答 3

5

在你的循环中试试这个:

Integer.parseInt(letter, 36);

这将解释letter为 base36 数字(0-9 + 26 个字母)。

Integer.parseInt("2", 36); // 2
Integer.parseInt("B", 36); // 11
Integer.parseInt("z", 36); // 35
于 2012-12-05T07:38:01.057 回答
2

您可以在循环中使用这一行(假设用户没有输入空字符串):

int x = Character.isDigit(temp[i].charAt(0)) ?
        Integer.parseInt(temp[i]) : ((int) temp[i].toLowerCase().charAt(0)-87) ;

numValue.add( x );

上面代码的解释:

  • temp[i].toLowerCase()=> z 和 Z 将转换为相同的值。
  • (int) temp[i].toLowerCase().charAt(0)=>字符的ASCII码。
  • -87=> 为您的规格减去 87。
于 2012-12-05T07:24:59.383 回答
1

考虑到您想将 Z 表示为 35,我编写了以下函数

更新 :

Z 的 ASCII 值为 90,因此如果要将 Z 表示为 35,则应将 55 中的每个字符减去 (90-35=55):

public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
    if (sarray != null) {
        int intarray[] = new int[sarray.length];
        for (int i = 0; i < sarray.length; i++) {
            if (sarray[i].matches("[a-zA-Z]")) {
                intarray[i] = (int) sarray[i].toUpperCase().charAt(0) - 55;
            } else {
                intarray[i] = Integer.parseInt(sarray[i]);
            }
        }
        return intarray;
    }
    return null;
}
于 2012-12-05T07:35:55.757 回答