Programming43343443 Programming43343443 - 20 days ago 11
Java Question

How to put two numbers separated by a space into two different arrays

I have two number inputs

1010 212

I want to put these into two different arrays ([1 0 1 0] and [2 1 2])

This is my code

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
int Array[] = new int[8];
int Array2[] = new int[8];
int i = 0;
Scanner getNumber = new Scanner(System.in);
do {
Array[i] = getNumber.nextInt();
i++;
} while(getNumber.hasNextInt());


System.out.println(Arrays.toString(Array));

}
}


But I get this as an output

[1010, 212, 0, 0, 0, 0, 0, 0]

(I put 8 as a generic array length because the java compiler forced be to initialize each array)

Answer

You need to store the numbers first then initialize your arrays based on the length of your number. You can get the length by turning it into a string. Once you are left with a number and an empty array, you can split an integer into an array of its digits a number of ways.

int[] array, array2;
Scanner in = new Scanner(System.in);

int a, b;

a = in.nextInt();
b = in.nextInt();

array = new int[Integer.toString(a).length()];
array2 = new int[Integer.toString(b).length()];

int i = 0;
while(a > 0) {
    array[i] = a % 10;
    a /= 10;
    i++;
}

i=0;
while(b > 0) {
    array2[i] = b % 10;
    b /= 10;
    i++;
}

System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(array2));
Comments