我试图从文本文件中读取点和X网格,并将它们添加到数组中并将它们打印为一个大网格。出于某种原因,它以阵列的形式打印阵列的部分,在控制台的这些块之间有大的空间。如果我使用toString它打印内存位置,所以我不知道这里发生了什么...
代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in); // Created a scanner
System.out.println("Enter the file name you would like to use");
File file = new File(input.nextLine()); // Takes file name to find file
Scanner inputFromFile = new Scanner(file);
String line = inputFromFile.nextLine();
FileInputStream fileInput = new FileInputStream(file); // reads file
int r;
while ((r = fileInput.read()) != -1) { // goes through each character in
// file, char by char
char c = (char) r;
for (int i = 0; i <= 4; i++) {
for (int y = 0; y <= 3; y++) {
GameOfLife.grid[i][y] = c;
for (int j = 0; j < GameOfLife.grid.length; j++)
System.out.println(GameOfLife.grid[j]);
}
}
}
}
}
GameOfLife:
import java.util.Arrays;
public class GameOfLife {
static final int m = 25; // number of rows
static final int n = 75; // number of columns
static char[][] grid = new char [m][n]; // Creates an empty (no dots or X's)grid of rows and columns.
}
答案 0 :(得分:1)
尝试在while循环之外打印数组的内容。您正在做的是在每个字符添加到网格后打印网格的所有内容
答案 1 :(得分:0)
您正在每个角色后打印网格。
您需要以下内容:
// Walk the whole grid.
for (int i = 0; i <= 4; i++) {
for (int y = 0; y <= 3; y++) {
// Read a character from the file.
int r = fileInput.read();
if (r != -1) {
GameOfLife.grid[i][y] = (char) r;
} else {
// End of file before grid filled!!! TODO! Deal with this.
}
}
}
// Print out the results.
for (int j = 0; j < GameOfLife.grid.length; j++) {
System.out.println(GameOfLife.grid[j]);
}