0

I am trying to take a 4 digit number a user enters and split it into an array of digits. So for example a user enters the number "2000" and it is split into [2,0,0,0].

I have tried this, but it does not work.

Scanner myObj = new Scanner (System.in);
        System.out.println("Enter 4 numbers");

        int userNumbers = myObj.nextInt();
        
        int[] array = new int [4];
        
          array[0] = userNumbers[0];
          array[1] = userNumbers[1];
          array[2] = userNumbers[2];
          array[3] = userNumbers[3]; 

I have also tried which works nicely but it is converting the numbers to strings in the array. I need an array of integers.

Scanner myObj = new Scanner (System.in);
        System.out.println("Enter 4 numbers");

        int userNumbers = myObj.nextInt();
       
        String[] digits = Integer.toString(userNumbers).split("");
        System.out.println(Arrays.toString(digits));

I am literally just beginning Java so I am aware this is quite basic stuff. I just need a point in the right direction. Thanks a lot!

0 Answers0