简体   繁体   English

Java String.charAt()无法正常工作

[英]Java String.charAt() not working properly

I'm trying to read in a grid from a text file to construct a graph out of it. 我正在尝试从文本文件中读取网格以从中构造图。

Goal nodes are indicated by a X while other nodes are indicated by a . 目标节点用X表示,其他节点用表示. .

I have the number of rows and the number of columns as well. 我也有行数和列数。 So, I'm basically just trying to read in the next line for each row, then get the character at each column location by passing the iterator for column location and check it against an X to see if it should be marked as a goal node. 因此,我基本上只是尝试读取每一行的下一行,然后通过传递用于列位置的迭代器来获取每个列位置处的字符,并针对X进行检查以查看是否应将其标记为目标节点。

goalGraph = new int[rows][cols];
for (int i = 0; i < rows; i++) {
    String readLine = in.nextLine();
    System.out.println(readLine);
    for (int ii = 0; ii < cols; ii++) {
        char c = readLine.charAt(ii);
        if (c == 'x') {
            goalGraph[i][ii] = 1;
        }
        else {
            goalGraph[i][ii] = 0;
            System.out.print(".");
        }
    }
}

But I keep getting an arrayoutofbounds error at index (0) . 但是我一直在index (0)处遇到arrayoutofbounds错误。

Another strange thing is that it is not printing readLine when the lower code is implemented, but taking it out so it looks like: 另一个奇怪的事情是,在实现下面的代码时,它不打印readLine ,而是将其取出,因此看起来像:

goalGraph = new int[rows][cols];
for (int i = 0; i < rows; i++) {
    String readLine = in.nextLine();
    System.out.println(readLine);
    /**
    for (int ii = 0; ii < cols; ii++) {
        char c = readLine.charAt(ii);
        if (c == 'x') {
            goalGraph[i][ii] = 1;
        }
        else {
            goalGraph[i][ii] = 0;
            System.out.print(".");
        }
    }
    **/
}

As a result, the line being read in are printed, and I get the correct string: 结果,打印出正在读取的行,并且我得到了正确的字符串:

X.....

...X..

......

.X....

Can anyone point me in the right direction? 谁能指出我正确的方向?

Thanks! 谢谢!

There is nothing obviously wrong with the code you've shown. 您显示的代码显然没有错。 We need to see more. 我们需要看更多。 Probably what is happening is that there aren't actually rows rows of data in your input. 也许正在发生的事情是,有没有实际rows中输入数据的行。 How are rows and cols generated? 如何rowscols产生的? What type is in , and how is it initialized? 是什么类型in ,以及它是如何初始化? What line does the arrayoutofbounds error happen at? arrayoutofbounds错误发生在哪一行?

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

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