如何将int of zeros转换为int[](数字数组)



当我尝试时,它不起作用。

class Main{
    public static void main(String[] args) {
        int num = 000000;
        String temp = Integer.toString(num);
        int[] numbers = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            numbers[i] = temp.charAt(i) - '0';
        }
        System.out.println(Arrays.toString(numbers));
    }
}

它只输出一个零。

使用Arrays类将字符串decimal digits转换为这些数字的int array

String digitString = "000000";
int[] digits = new int[digitString.length()];
Arrays.setAll(digits, i-> digitString.charAt(i)-'0');
System.out.println(Arrays.toString(digits));

打印

[0,0,0,0,0,0]

如果数字都相同,有更简单的方法。但以上内容适用于任何十进制数字的字符串。

int num = 000000;

这与相同

int num = 0;

相反,从字符串开始,然后继续

class Main{
    public static void main(String[] args) {
        String temp = "000000";
        int[] numbers = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            numbers[i] = temp.charAt(i) - '0';
        }
        System.out.println(Arrays.toString(numbers));
    }
}

或者,如果你只想在数组中使用零,你也可以使用

int[] numbers = new int[6]

你甚至可以这样做,并添加任何你喜欢的数字

int[] numbers = new int[5]//will make an array of size 5 with all elements 0
Arrays.fill(numbers, 1);//will set all elements to 1

最新更新