我正在尝试读取文本文件并创建一个数组。使用出现在第一行的文件的前 2 个值设置数组。然后将文件中的所有剩余项添加到数组中。由于某种原因,我的数组也总是空的。需要进行哪些更正才能使其正常运行?
public static Grid createGrid(String filename) throws IOException {
BufferedReader input;
String inputLine;
char[][] grid;
Grid currentGrid;
int currentLine = 0;
try{
input = new BufferedReader(new FileReader(filename));
inputLine = input.readLine();
String[] tokens = inputLine.split(" ");
if(tokens.length != 2){
throw new IllegalArgumentException();
}
int height = Integer.parseInt(tokens[0]);
int width = Integer.parseInt(tokens[1]);
grid = new char[height][width];
while(inputLine != null){ // Giving me (Condition 'inputLine != null' is always 'true') in ide
System.out.println(inputLine);
inputLine = input.readLine();
for(int i = 0; i < inputLine.length() - 1; i++){
char currentGem = inputLine.charAt(i);
grid[currentLine][i] = currentGem;
}
currentLine++;
}
input.close();
currentGrid = new Grid(grid);
}
catch(IOException e){
System.out.println(e.getMessage());
currentGrid = null;
}
return currentGrid; // Giving me (Value 'currentGrid' is always 'null') in ide
}
在你的代码中...
while(inputLine != null(
。将始终true
inputLine
因为这是您的String
,并且在运行此检查时它将始终具有值。原因是因为一旦您将null
读入inputLine
(当您到达文件末尾时(,而不是运行循环检查,而是在尝试运行下一行代码时抛出NullPointerException
......for(int i = 0; i < inputLine.length() - 1; i++)
.这反过来将导致currentGrid
始终null
,因为它在那时仍被声明为null
。
要解决此问题,您只需要在while
之前添加一个inputLine = input.readLine();
,然后将while
中的同一行移动到while
的末尾,如下所示...
public static Grid createGrid(String filename) throws IOException {
Grid currentGrid = null;
try {
BufferedReader input = new BufferedReader(new FileReader(filename));
String inputLine = input.readLine();
String[] tokens = inputLine.split(" ");
if(tokens.length != 2){
throw new IllegalArgumentException();
}
int height = Integer.parseInt(tokens[0]);
int width = Integer.parseInt(tokens[1]);
char[][] grid = new char[height][width];
int currentLine = 0;
inputLine = input.readLine(); // added before while
while(inputLine != null) {
System.out.println(inputLine);
for(int i = 0; i < inputLine.length() - 1; i++){
char currentGem = inputLine.charAt(i);
grid[currentLine][i] = currentGem;
}
currentLine++;
inputLine = input.readLine(); // last line in while
}
input.close();
currentGrid = new Grid(grid);
}
catch(IOException e) {
System.out.println(e.getMessage());
currentGrid = null;
}
return currentGrid;
}
哦,你也会注意到我移动了你的声明。您不必声明BufferedReader input
、String inputLine
和char[][] grid
超出您的try { ... } catch
块。此外,您只需在需要之前声明int currentLine = 0;
(这只是很好的做法(。