[英]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.