0

im trying to print out a text file into a grid-like format after pulling them from a text file. Similar to this method, creating a 2 level for looping going through each row and column. However im not sure the process how it differs when dealing with characters rather than numbers.

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

thank you

Community
  • 1
  • 1
Silverfin
  • 485
  • 6
  • 17

1 Answers1

0

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

Most of the problems are answered in that link. First of all you are not assigning anything into the array. I'll copy my answer from that link here.

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

Update: I see your file don't have a regular number of characters in each line. You'll have to count the number of lines for the height and the number of characters in the longest line for the width or you could just input them yourself.

Community
  • 1
  • 1
gallickgunner
  • 472
  • 5
  • 20