0

everyone. I have been thinking this for 3 hours, just cannot figure out. I have a program that requires reading the file into a 2D array. The file is like:

...##..#####........
########....####..##
.........##.........
#.#.#.#.#.#.#.#.#.#.

Basically, it is about a seat reservation system.

" . "means opened seats. " # " means reserved seats. The row and col are unknown to me, depend on the file. But every row has the same number of seats.

import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;


public class Main 
{   


public static void main(String[] args)  throws Exception 
{


    int rows = 0, cols = 0;
    char[][] auditorium = new char[rows][cols];

    Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));

 }

I am new to java, really don't have any thoughts on this program. Please read the file and put the data into a char 2D array.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Combine the answers from https://stackoverflow.com/questions/2049380/reading-a-text-file-in-java and https://stackoverflow.com/questions/10751603/how-to-insert-values-in-two-dimensional-array-programmatically to get what you want. – jrook Feb 04 '20 at 00:18
  • Maybe use readLine and then toCharArray – Scary Wombat Feb 04 '20 at 00:23
  • Also note that your `auditorium` array has been initialized with 0 rows and 0 columns. If you try to insert anything into this array, you could get an index out of exception. You could use a data structure that does not need to know the size of the input beforehand. An `ArrayList` might be useful to get around such problems. – jrook Feb 04 '20 at 01:23

1 Answers1

0

Please check this code. It'll may help to you:

public static void main(String[] args) throws Exception {
    List<String> stringList = new ArrayList<>();
    Scanner sc = new Scanner(new BufferedReader(new FileReader("A1.txt")));
    while (sc.hasNext()) {
        stringList.add(sc.nextLine());
    }
    int rows = stringList.size();
    int cols = 0;
    if (rows > 0) {
        cols = stringList.get(0).length();
    }
    char[][] auditorium = new char[rows][cols];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            auditorium[i][j] = stringList.get(i).charAt(j);
        }
    }
}
Anuradha
  • 570
  • 6
  • 20