简体   繁体   English

Java读取字符串到2D布尔数组

[英]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. 我试图读取一个txt文件,其中包含#和空格到2D布尔数组,因此从技术上讲,#表示true,空格表示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]; 在我编写的代码中,我写了boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. 它说[x][y]需要一个int,但是找到了一个字符串。 The same issue is for cells[finalX][finalY] = true; 同样的问题是针对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: "#####################" 我试过解析即Integer.parseInt(x)然而这给我一个错误: 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? 如果我解析为Int,那么它无法读取#correct?

It says the [x] and [y] requires an int, but found a string. 它说[x]和[y]需要一个int,但是找到了一个字符串。 The same issue is for cells[finalX][finalY] = true; 同样的问题是针对单元格[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: "#####################" 我试过解析即Integer.parseInt(x)然而这给我一个错误:线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“################ #####”

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. 此外,您的if condition似乎没有正确执行操作。 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 . 1-读取每行文件直到它的结尾以获得n的单元格行数,然后获取任何String行的长度以获得m的列数。

2- create boolean array cells[n][m] . 2-创建布尔数组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 . 由线3-读取文件中的行,并把每一行中字符串变量和迭代字符串变量字符,如果字符是#true中的细胞阵列否则把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). 在尝试使用文件之前你应该学习更基本的东西,你甚至不能正确初始化数组,你使用字符串作为大小和索引导致你提到的那些问题,另一个初学者错误是试图解析非整数字符串to int(你试图将############转换为int,这是不可能的,如果你知道字符串是1或5或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. 所以我对你的问题的回答是慢慢地学习基础知识,然后逐步添加新的东西,而不是急于求成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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