简体   繁体   中英

Java Reading Strings to a 2D Boolean Array

I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.

With the help of similar posts i got together a code, although they were reading integers to an array.

My code is:

public static void main(String[] args) {
    String x;
    String y;
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    x = fileName.nextLine();
    y = fileName.nextLine();

    boolean[][] cells = new boolean[x][y];

    String finalX = fileName.nextLine();
    String finalY = fileName.nextLine();
    cells[finalX][finalY] = true;

    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells[i].length; j++) {
            if (cells[i][j])
                System.out.print("#");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}

In my code where I have written boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing ie Integer.parseInt(x) however this gets me an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

At what point is my issue? If I parse to an Int, then it can't read the # correct?

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing ie Integer.parseInt(x) however this gets me an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

One approach you could do is first read the entire file.

Example:

List<String> tempList = new ArrayList<>();

while (fileName.hasNextLine()) {
     String line = fileName.nextLine();
     tempList.add(line);
}

then you can do this:

boolean[][] cells = new boolean[tempList.size()][tempList.get(0).length()];

note - this solution assumes the length() of each line is the same and the columns of each line is the same.

Also, why do you need to perform this outside the loop?

cells[finalX][finalY] = true;

you should remove that line and let the loop do all the work to determine what's # or ' ' . Also, your if condition doesn't seem to be doing the correct operation. Consider implementing this approach and then go on from there.

I think this would solve it:

1- read each line of file until the end of it to get the number of cells rows which is n then take length of any String line to get number of columns which is m .

2- create boolean array cells[n][m] .

3- read file line by line and put each line in String variable and iterate over the string variable characters if character is # put true in cells array otherwise put false .

      String line="";
      int n=0;
      while(fileName.hasNextLine()){
        line = fileName.nextLine();
        n++;
      }
      int m = line.length();
      boolean[][] cells = new boolean[n][m];
      // initialize Scanner to read file again
      Scanner in = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
      int i=0;
      while(in.hasNextLine()){
            line = in.nextLine();
        for(int j=0; j < line.length(); j++){
            char c = line.charAt(j);    
            if(c == '#'){
                cells[i][j] = true;
            }
            else{
                cells[i][j] = false;
            }
        }
        i++;
     }

You have many mistakes in code and this approach is definitely wrong, you don't even save values that you read from file inside array. Also this code is simply not how you do it, for reading files where you don't know length of file you want to use Lists where you don't need to specify number of elements that list will take(its possible to do get semi-working solution with arrays but there is no point of learning something that is simply wrong). Before even trying to work with files you should learn more basic things, you don't even initialize your arrays properly, you use string for size and index which is causing those issues you mentioned, another beginner mistake is trying to parse non-integer string to int(you are trying to convert ############ to int which is impossible, you can only use this if you know that string is an integer like 1 or 5 or 1000). So my answer to your question is to just go slowly and learn basics then add new stuff step by step instead just rushing with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM