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.

3
  • Combine the answers from stackoverflow.com/questions/2049380/reading-a-text-file-in-java and stackoverflow.com/questions/10751603/… to get what you want. Commented Feb 4, 2020 at 0:18
  • Maybe use readLine and then toCharArray Commented Feb 4, 2020 at 0: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. Commented Feb 4, 2020 at 1:23

1 Answer 1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used answer suggested by @jrook to create this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.