简体   繁体   English

读取整数到2D数组

[英]Reading in integers to a 2D array

I need help with reading integers into a 2D square array of N x N dimensions. 我需要将整数读入N x N维的2D正方形数组中的帮助。

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 同样在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. 原因是Java扫描程序将整数(例如:123)当作一个数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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