简体   繁体   中英

Reading in integers to a 2D array

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.

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

The reason is java scanner gets whole number (eg: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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM