Reputation:
I need help with reading integers into a 2D square array of N x N dimensions.
For example, if the user input is:
123
333
414
Then I will need an array:
{
{1, 2, 3},
{3, 3, 3},
{4, 1, 4}
}
The problem that I am having is that there is no space between these integers. If there were a space, I could just do
for (int i = 0 ; i < N; i++) {
for(int j = 0; j < N ; j++) {
myArray[i][j] = scan.nextInt();
}
}
I approached this problem by trying to use substrings and parsing it into the array, although I did not get anywhere.
Another approach (Edit)
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
myArray[i][j] = Integer.parseInt(scan.nextLine().substring(j, j+1));
}
}
This does not work either - it keeps running after the three lines are entered.
Upvotes: 0
Views: 134
Reputation: 3115
Perhaps this helps:
public static void main( String[] args ) {
Scanner scanner = new Scanner( System.in );
int[][] array = new int[3][3];
for ( int[] ints : array ) {
char[] line = scanner.nextLine().toCharArray();
for ( int i = 0; i < line.length; i++ ) {
ints[i] = Character.getNumericValue( line[i] );
}
}
Arrays.stream( array ).forEach( x -> System.out.println( Arrays.toString( x ) ) );
}
Also with Java 8
public static void main( String[] args ) {
Scanner scanner = new Scanner( System.in );
int[][] array = new int[3][3];
for ( int[] ints : array ) {
ints = scanner.nextLine().chars().map( Character::getNumericValue ).toArray();
}
Arrays.stream( array ).forEach( x -> System.out.println( Arrays.toString( x ) ) );
}
Upvotes: 1
Reputation: 176
The reason is java scanner gets whole number (e.g:123) as a one number.
for (int i = 0 ; i < N; i++) {
int p = scan.nextInt();
for (int j = N-1; j >= 0; j--) {
array[i][j] = p % 10;
p = p / 10;
}
}
Upvotes: 0