首页 > 解决方案 > 将字符串值添加到数组索引时出错

问题描述

public class aa {
    public static void main(String[] args) {
        int number = 521;
        String temp1 = "" + number;
        int result = 0;
        int[] temp2 = new int[temp1.length()];
        for(int i=0; i<temp1.length(); i++){
            int len = temp1.length();
            temp2[i] = temp1.charAt(len-i-1);
            System.out.println(temp2[i]);
            System.out.println(temp1.charAt(len-i-1));
        }

    }
    
}

这个程序应该使 521 到 125(反向)。但是当我运行这个程序时,结果是

49
1
50
2
53
5

我认为字符串值是正确的,但是当我将该字符串值添加到数组时,它会出错。有人可以告诉我出了什么问题吗?

标签: javaarraysstringfor-loopindexing

解决方案


正如我在评论中所说,temp2是错误的类型。您将其声明为ints 的数组,因此 sprintln当然是将其视为数字数组,而不是可打印字符的数组。

只需将temp2类型更改为char[]

public class aa {
    public static void main(String[] args) {
        int number = 521;
        String temp1 = "" + number;
        int result = 0;
        char[] temp2 = new char[temp1.length()];
        for(int i=0; i<temp1.length(); i++){
            int len = temp1.length();
            temp2[i] = temp1.charAt(len-i-1);
            System.out.println(temp2[i]);
            System.out.println(temp1.charAt(len-i-1));
        }

        // print the whole reversed number on one line
        for(char c : temp2) {
            System.out.print(c);
        }

        System.out.println();
    }
    
}

输出

1
1
2
2
5
5
125

当然,这不是最佳解决方案,只是一种修复您编写的代码以使其正常工作的方法。请参阅Alex Rudenko 的评论,以获取有关反转数字数字问题的更好解决方案的链接。


推荐阅读