Home > Mobile >  How do I convert int of zeros to int [] (array of digts)?
How do I convert int of zeros to int [] (array of digts)?

Time:01-02

This did not work when I tried it.

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

    }
}

it only outputs one zero.

CodePudding user response:

int num = 000000;

This is the same as

int num = 0;

Instead start with a string and then continue

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

    }
}

Or if you just want zeroes inside the array you could also just do this

int[] numbers = new int[6]

You could even do this and add any number you like

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

CodePudding user response:

Use the Arrays class to convert a string of decimal digits to an int array of those digits.

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

prints

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

There are simpler ways if the digits are all the same. But the above will work for a string of any decimal digits.

  •  Tags:  
  • java
  • Related