我的方法能够读取文件的所有行,但随后它会卡在最后一行,永远不会到达scanner.close()
及以后。我不知道为什么?我调用scanner.nextLine()
所以它肯定会检测到这一点,scanner.hasNextLine()
应该在文件结束时返回false。我在这里忽略了一个快速解决方案吗?
private int[] GetNumberOfRowsAndColumns(BufferedReader br) {
Scanner scanner = new Scanner(br);
String line = "";
int column_max = 0;
int total_rows = 0;
int[] result = new int[1];
try {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.length() > column_max) {
column_max = line.length();
}
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
}
scanner.close();
result[0] = column_max;
result[1] = total_rows;
return result;
}
有问题的文件:
+++++++++++++++++
+0A +
+AA ++++
+ +
+ ++A+
+ +a+
+++++++++++++++++
编辑:
public SearchClient(BufferedReader serverMessages) throws Exception {
Map<Character, String> colors = new HashMap<Character, String>();
String line, color;
int agentCol = -1, agentRow = -1;
int colorLines = 0, levelLines = 0;
// Read lines specifying colors
while ((line = serverMessages.readLine())
.matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) {
line = line.replaceAll("\\s", "");
String[] colonSplit = line.split(":");
color = colonSplit[0].trim();
for (String id : colonSplit[1].split(",")) {
colors.put(id.trim().charAt(0), color);
}
colorLines++;
}
if (colorLines > 0) {
error("Box colors not supported");
}
int[] result = getNumberOfRowsAndColumns(serverMessages);
System.err.println("MAX COLUMNS = " + result[0]);
System.err.println("MAX ROWS = " + result[1]);
initialState = new Node(null);
while (!line.equals("")) {
for (int i = 0; i < line.length(); i++) {
char chr = line.charAt(i);
if ('+' == chr) { // Walls
initialState.walls[levelLines][i] = true;
} else if ('0' <= chr && chr <= '9') { // Agents
if (agentCol != -1 || agentRow != -1) {
error("Not a single agent level");
}
initialState.agentRow = levelLines;
initialState.agentCol = i;
} else if ('A' <= chr && chr <= 'Z') { // Boxes
initialState.boxes[levelLines][i] = chr;
} else if ('a' <= chr && chr <= 'z') { // Goal cells
initialState.goals[levelLines][i] = chr;
}
}
line = serverMessages.readLine();
levelLines++;
}
}
答案 0 :(得分:2)
按照惯例,Java方法以小写字母开头。接下来,您的数组只能包含一个值(长度为1),而您不需要Scanner
(使用BufferedReader
)。最后,您可以创建一个匿名数组。像,
private int[] getNumberOfRowsAndColumns(BufferedReader br) {
int column_max = 0;
int total_rows = 0;
try {
String line;
while ((line = br.readLine()) != null) {
// if (line.length() > column_max) {
// column_max = line.length();
// }
column_max = Math.max(column_max, line.length());
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new int[] { column_max, total_rows };
}