因此,我得到的字符串索引超出范围意味着我超出了集合的范围,但我不太确定我是如何使用我的代码执行此操作的。Java字符串索引超出范围
该代码应该从包含3个整数的文本文件(前两个分别与行数和列数相关)以及一系列字符中读取。所以首先读取并保存前三个数字,然后将文件的其余部分转换为字符串。然后,通过设置一个带有文本文件尺寸的字符数组,然后用字符逐个字符地填充文本文件的字符来填充这些值。
但是,当我尝试打印出代码时,遇到字符串索引超出范围错误并且找不到问题。
这是代码:
import java.util.*;
import java.io.*;
public class SnakeBox {
// instance variables
private char[][] box;
private int snakeCount;
private int startRow, startCol;
private int endRow, endCol;
private int rows, cols, snakes;
Scanner keyboard = new Scanner(System.in);
/** Create and initialize a SnakeBox by reading a file.
@param filename the external name of a plain text file
*/
public SnakeBox(String fileName) throws IOException{
Scanner infile = new Scanner(new FileReader(fileName));
int count = 0;
String s = "";
rows = infile.nextInt();
cols = infile.nextInt();
snakes = infile.nextInt();
infile.nextLine();
box = new char[rows][cols];
while (infile.hasNext()) {
s += infile.next();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
count++;
char c = s.charAt(count);
box [i][j] = c;
}
}
}
的文本文件是:
16 21 4
+++++++++++++++++++++
+ +
+ SSSSS +
+ S S +
+ S SS +
+ S S +
+ S S SS +
+ SS S +
+ S +
+ S SSSSSS +
+ S S +
+ S S +
+ S SSS S +
+ S S +
+ SSSSS +
+++++++++++++++++++++
谢谢。
检查文档http://docs.oracle.com/javase/1.5.0/docs/ api/java/util/Scanner.html#next%28% 就像Achintya所说的next()返回一个标记。文件中的所有空白都会被忽略。 – Alex 2013-04-05 09:27:22
嗯谢谢你,这是一个大问题,我怎么能够保存我阵列中的空白空间呢? – user2248256 2013-04-05 09:27:53
+1。我没有看到这 – gefei 2013-04-05 09:31:17