从文本文件中读取整数并将它们放在2D数组中(Java)

时间:2015-03-22 18:27:07

标签: java arrays parseint

我有一个带整数的文本文件:

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

1 个答案:

答案 0 :(得分:3)

要从文件中读取,请使用x扫描仪方法更改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
    }
 }