【问题标题】:Reading integers from a text file and placing them in a 2D array (Java)从文本文件中读取整数并将它们放入二维数组(Java)
【发布时间】:2015-03-22 18:27:07
【问题描述】:

我有一个包含整数的文本文件:

6 3 4 15  
9 5 14 8  
12 0 1 10  
13 11 7 2 

(全部用空格隔开)

我需要使用扫描仪读取这些内容,然后将它们放入 4x4 矩阵中。

    state = new int [sizeOfPuzzle][sizeOfPuzzle];
    isSolved = false;

    IODialog input = new IODialog();
    String location = input.readLine("Enter the full path of the configuration text file: ");
    File temp = new File (location);
    Scanner file = new Scanner (temp);
    while (file.hasNextInt())
    {
        int x=0;
        for (int i=0; i<sizeOfPuzzle; i++)
        {
             for (int j=0; j<sizeOfPuzzle; j++)
             {
                 state[i][j]=x;
                 x++;   
             }  
        }
    }

【问题讨论】:

  • 为什么要增加 x 而不是从扫描仪读取?

标签: java arrays parseint


【解决方案1】:

要从文件中读取,请将 x 更改为 Scanner 的 nextInt() 方法。

 for (int i=0; i<sizeOfPuzzle; i++){
    for (int j=0; j<sizeOfPuzzle; j++){
     state[i][j]=sc.nextInt();
      //Choose a good name for Scanner object like sc instead of file
    }
 }

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多