【问题标题】:Import one-dimensional string to two-dimensional int array将一维字符串导入二维 int 数组
【发布时间】:2018-08-22 22:13:06
【问题描述】:

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

Example of a couple of printed boards:

这是第一块板: 370000001000700005408061090000010000050090460086002030000000000694005203800149500

前 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) {

    }

此代码可以在文本文件中导入单个整数,例如:

0
1
3
5
0
8
etc

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

或者我如何创建一个新的程序来填充相同的功能?

【问题讨论】:

    标签: java arrays import int sudoku


    【解决方案1】:

    使用scanner.nextLine 读取该行并使用Integer.parseIntchar 转换为int

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

    【讨论】:

      【解决方案2】:

      如果您使用的是 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
      

      输出

      [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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-04
        • 2020-09-02
        • 1970-01-01
        • 2019-01-23
        • 2021-06-12
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        相关资源
        最近更新 更多