在给定包含字符的文本文件的情况下填充和打印2D数组

时间:2016-02-07 08:45:43

标签: java arrays for-loop multidimensional-array

我尝试将文本文件从文本文件中拉出后,将其打印成类似网格的格式。与this method类似,为每个行和列创建一个2级循环。但是,在处理字符而不是数字时,我不确定它的不同之处。

example of text file im trying to replicate, excluding the first numbers

8 10
+-+-+-+-+-+-+-+-+-+  
|                 |  
+ +-+-+-+ +-+-+-+ +  
| |             | |  
+ + +-+-+-+-+-+ + +  
| | |         | | |  
+ + + +-+-+-+ + + +-+
| | | |     | | |  S|
+ + + + +-+ + + + +-+
| |   |   |E| | | |  
+ + + +-+ +-+ + + +  
| | |         | | |  
+ + +-+-+-+-+-+ + +  
| |             | |  
+ +-+-+-+-+-+-+-+ +  
|                 |  
+-+-+-+-+-+-+-+-+-+  


static void readMazeFile(String mazefile) throws FileNotFoundException {
    Scanner mazeIn = new Scanner (new File (mazefile));
    int height = mazeIn.nextInt();
    int width = mazeIn.nextInt();
    System.out.print(width);
    System.out.print(height);

    // get array height & width

    int arrayHeight = (height*2)+1;
    int arrayWidth = (width*2)+1;
    System.out.print(arrayHeight);
    System.out.print(arrayWidth);

    // create new array set variables
    char mazeAsArray[][] = new char[arrayHeight][arrayWidth];
    int charCount = 0;

    //populate and print array
    System.out.print("-------------\n");
    for (int r = 0; r < 9; r++){
        for (int c = 0; c < 9; c++){
            System.out.print(mazeAsArray[r][c]);
        }
    }
}

谢谢

1 个答案:

答案 0 :(得分:0)

How do i get characters in a file into a 2D array in Java?

大多数问题都在该链接中得到解答。首先,你没有在数组中分配任何东西。我会在这里复制我的答案。

    for (int row = 0; row < arrayheight; row++) 
    {
          if(!mazein.hasNextLine())
                break;            // if there is no more lines to read, break the loop 
          String line = mazein.nextLine();
          Char[] chars = line.toCharArray();

          for (int col = 0, i = 0; (col < arraywidth && i < chars.length); col++,i++) 
          {
            mazeAsArray[row][col] = chars[i];
            System.out.print(mazeAsArray[row][col]);
          }
    }

更新: 我看到你的文件中每行都没有常规字符数。您必须计算高度的行数和宽度最长行中的字符数,或者您可以自己输入它们。