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);

これはletterbase36 の数値 (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

ループ内でこの 1 行を使用できます (ユーザーが空の文字列を入力しないと仮定します)。

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 に答える