首先,感谢您的到来,并花时间帮助解决问题。
我是一个完整的菜鸟(第3天编程),这解释了为什么我花费了无数时间来试图解决这个问题,但仍然没有想到它:
问题:如何扫描包含字符串(*和_)的.txt文件并将其转换为布尔数组(即* = true和_ = false)(另外如何将其打印出来?我猜我们还需要一个双循环for)?扫描程序似乎不在main方法中工作,我得到一个'没有这样的文件'错误。
红利问题:你如何迭代网格(例如使用for循环),以便新网格替换旧网格,最新网格成为新网格不停?我不熟悉' show()'方法,但我有点工作。
这是我不完整的代码,可以让您了解问题:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class GameOfLife {
public static boolean[][] gen() throws IOException {
Scanner scanner = new Scanner(new File("seed.txt"));
int rows = 0, columns = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (s.length() > columns)
columns = s.length();
rows++;
}
boolean[][] grid = new boolean[rows][columns + 1];
Scanner scanner1 = new Scanner(new File("seed.txt"));
String line;
for (int r = 0; r < rows; r++) {
line = scanner1.nextLine();
System.out.println(line);
for (int c = 0; c <= line.length(); c++) {
if (r == line.length()) {
break;
}
if(line.charAt(r) == '*') {
grid[r][c] = true;
}
}
}
return grid;
}
public static boolean[][] nextGen(boolean[][] cells){
boolean[][] newCells = new boolean[cells.length][cells[0].length];
int num;
for(int r = 0; r < cells.length; r++){
for(int c = 0; c < cells[0].length; c++){
num = numNeighbours(cells, r, c);
if (occupiedNext(num, cells[r][c]))
newCells[r][c] = true;
}
}
return newCells;
}
public static void main(String[] args) throws IOException{
boolean[][] cells = gen();
show(cells);
cells = nextGen(cells);
show(cells);
Scanner scanner2 = new Scanner(new File("seed.txt"));
while(scanner2.nextLine().length() != 0){
cells = nextGen(cells);
show(cells);
}
}
private static boolean inbounds(boolean[][] cells, int r, int c) {
return r >= 0 && r < cells.length && c >= 0 &&
c < cells[0].length;
}
private static int numNeighbours(boolean[][] cells, int row, int col) {
int num = cells[row][col] ? -1 : 0;
for (int r = row - 1; r <= row + 1; r++)
for(int c = col - 1; c <= col + 1; c++)
if (inbounds(cells, r, c) && cells[r][c] )
num++;
return num;
}
public static void show(boolean[][] grid){
String s = "";
for(boolean[] row : grid){
for(boolean val : row)
if(val)
s += "*";
else
s += "_";
s += "\n";
}
System.out.println(s);
}
public static boolean occupiedNext(int numNeighbours, boolean occupied){
if (occupied && (numNeighbours == 2 || numNeighbours == 3))
return true;
else if (!occupied && numNeighbours == 3)
return true;
else
return false;
}
}
答案 0 :(得分:0)
我只是想建议一个可以帮到你的解决方案。尝试读取文件内容并分配到字符串变量中。现在使用string.replaceAll
方法(* and _)
到* = true and _ = false
。
比将更新的字符串写入文件。