[英]Method to fill 2d array with text file
目前,我正在开发一个创造生活游戏的项目,但是我被困在编写必须使用的第一种方法中。 基本上,它必须读取文本文件并将其填充为2d数组。 现在,我在主程序中得到一个错误,提示“线程“主程序中的异常” java.util.NoSuchElementException:找不到行。 任何帮助将不胜感激。 顺便说一句,我应该提到在文件中我知道行数,但是想要使其像我不知道行数/列数。
import java.util.*;
import java.io.*;
public class Proj5testing {
public static void main (String[] args)throws IOException{
Scanner inFile = new Scanner(new File("life4.txt"));
System.out.print(readBoard("life4.txt"));
}
public static int[][] readBoard(String filename)throws IOException{
int rows=0;
Scanner inFile = new Scanner(new File(filename));
while (inFile.hasNextLine()) {
rows++;
inFile.nextLine();
}
int cols=Integer.parseInt(inFile.nextLine());
int[][] grid=new int[rows][cols];
for(int i=0;i<grid.length;i++){
for(int k=0;k<grid[rows].length;k++){
grid[i][k]=inFile.nextInt();
}
}
return grid
}
}
看这段代码:
while (inFile.hasNextLine()) {
rows++;
inFile.nextLine();
}
这将循环直到没有更多的行。 当循环退出时(否则循环不会退出), hasNextLine()
将为false。
然后,立即致电:
int cols=Integer.parseInt(inFile.nextLine());
但是我们已经确定文件中没有下一行! 因此,当然会引发错误。
相反,您需要处理循环中的每一行。 我不知道您的文件的确切结构,但是可能是这样的:
int[][] grid=new int[rows][cols];
int col = 0;
int row = 0;
while (inFile.hasNextInt()) {
grid[col][row] = inFile.nextInt();
col = col + 1;
if (col == cols) { //wrap to the next row
row = row + 1;
col = 0;
}
}
问题是您正在尝试读取inFile
的下一行,但是由于您已经在while循环中读取了所有行,所以没有下一行。
您必须重新声明Scanner
对象才能再次从头读取。
当while循环结束时,扫描仪已到达文件末尾。 因此,没有更多的行(或整数)要读取。 要解决此问题,可以在for循环之前重新初始化扫描仪。
inFile = new Scanner(new File(filename));
您的代码还有其他一些问题。 看看下面的修改后的代码(这可能会做你想要的):
import java.util.*;
import java.io.*;
public class Proj5testing {
public static void main (String[] args) throws IOException {
// System.out.print(readBoard("life4.txt"));
// this will just print a referenceId; if you want to print the contents, you need to write a loop to iterate over all the elements
int[][] board = readBoard("life4.txt");
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
public static int[][] readBoard(String filename) throws IOException {
int rows = 0;
String line = "";
Scanner inFile = new Scanner(new File(filename));
while(inFile.hasNextLine()) {
rows++;
line = inFile.nextLine();
}
// int cols = line.split("\\s+").length;
// assuming that the file has space-separated integers in different lines
// e.g.
// 0 0 1 0 1
// 0 0 0 0 1
// 1 1 1 1 1
// since the file doesn't have space-separated integers, updating the answer
int cols = line.length();
// assuming that the file has lines in the following format
// 001001001
// 110011011
inFile = new Scanner(new File(filename));
// this will bring the scanner back to the start of the file
int[][] grid = new int[rows][cols];
for(int i = 0; i < rows; i++){
line = inFile.nextLine();
for(int k = 0; k < cols; k++){
grid[i][k] = line.charAt(k) - '0';
}
}
return grid;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.