Java 将一维字符串导入二维int数组

Java 将一维字符串导入二维int数组,java,arrays,import,int,sudoku,Java,Arrays,Import,Int,Sudoku,我想导入数独板并将其转换为[9][9]数组 这是第一块板: 3700000001000000700005408061090000010000500904600860020300000000000694005203800149500 前9个数字填充第一行,后9个数字填充第二行,以此类推 public static void main(String[] args) { File in = new File("board.txt"); try { Scanner i

我想导入数独板并将其转换为[9][9]数组

这是第一块板: 3700000001000000700005408061090000010000500904600860020300000000000694005203800149500

前9个数字填充第一行,后9个数字填充第二行,以此类推

 public static void main(String[] args) {
    File in = new File("board.txt");
    try {
        Scanner input = new Scanner(in);
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                grid[i][j]= input.nextInt();
            }

        }
    } catch (FileNotFoundException e) {

    }
那么,我该如何编辑我的代码,以便它可以“读取”一行没有空格的数字,并从元素的文本文件中导入每个数字呢


或者如何创建一个新程序来填充相同的函数?

使用
扫描器。下一行
读取该行并使用
整数。parseInt
字符
转换为
整数

    Scanner input = new Scanner(in);
    String line = input.nextLine();   
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            grid[i][j]= Integer.parseInt(line.charAt(i * 9 + j));
        }
    }
Scanner input=新扫描仪(in);
String line=input.nextLine();
对于(int i=0;i<9;i++){
对于(int j=0;j<9;j++){
grid[i][j]=Integer.parseInt(line.charAt(i*9+j));
}
}

如果您使用的是Java 8,则可以阅读所有行,然后可以执行以下步骤:

int[][] result = Arrays.asList(line.split("(?<=\\G.{9})"))//cut in each 9 element
        .stream()
        .map(row -> Stream.of(row.split(""))//Split each row
                        .mapToInt(Integer::parseInt).toArray()//convert it to array of ints
        ).toArray(int[][]::new);//Collect the result as a int[][]

Arrays.asList(result).forEach(row -> System.out.println(Arrays.toString(row)));//Print
int[][] result = Arrays.asList(line.split("(?<=\\G.{9})"))//cut in each 9 element
        .stream()
        .map(row -> Stream.of(row.split(""))//Split each row
                        .mapToInt(Integer::parseInt).toArray()//convert it to array of ints
        ).toArray(int[][]::new);//Collect the result as a int[][]

Arrays.asList(result).forEach(row -> System.out.println(Arrays.toString(row)));//Print
[3, 7, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 7, 0, 0, 0, 0, 5]
[4, 0, 8, 0, 6, 1, 0, 9, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 5, 0, 0, 9, 0, 4, 6, 0]
[0, 8, 6, 0, 0, 2, 0, 3, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[6, 9, 4, 0, 0, 5, 2, 0, 3]
[8, 0, 0, 1, 4, 9, 5, 0, 0]