Java: How to implement edge checking in Game of Life [duplicate] - java

I'm doing the Conway's game of life. I'm pretty sure I'm close to finished, but when I run it, I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at game.of.life.GameOfLife.generation(GameOfLife.java:77)
at game.of.life.GameOfLife.main(GameOfLife.java:32)
Java Result: 1
I'm assuming when the method that checks neighbors at the edges of the array, there's nothing there so it dies or something. I just don't know how to make it so that doesn't happen. Does anyone have any thoughts? Code below.
package game.of.life;
import java.util.Scanner;
public class GameOfLife {
static boolean[][] current = new boolean[10][10];
static boolean[][] old = new boolean[10][10];
static int population = 10;
public static void main(String[] args) {
String a = " # ";
String b = " ' ";
int choice = 9;
int gencount = 0;
Scanner input = new Scanner(System.in);
System.out.print("Choose population density. i.e. 10 = 10%: ");
population = input.nextInt();
populate();
copy();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
System.out.print("Generation " + gencount + ".");
while(choice != 0){
System.out.print("Make a selection: 1 - Advance Generation 0 - Exit");
choice = input.nextInt();
if(choice == 1){
generation();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
copy();
gencount += 1;
System.out.println("Generation" + gencount + ".");
}
}
}
private static void generation(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++){
if (old[r][c] == true){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors != 3 || neighbors != 2)
current[r][c] = false;
}
else if(old[r][c] == false){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors == 3)
current[r][c] = true;
}
}
}
}
private static void populate(){
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
int q = (int)(Math.random() * 100);
if(q < population){
current[r][c] = true;
}
else{
current[r][c] = false;
}
}
}
}
private static void copy(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++)
old[r][c] = current[r][c];
}
}
}
If anyone can help me out it would be much appreciated.

When r is 0, this one is not valid: old[r - 1][c].
Thus you get the exception you posted.
I suggest you simplify it like this.
boolean isValidPosition(int r, int c){
return
0 <= r && r < N &&
0 <= c && c < M;
}
int getNeighboursCount(boolean[][] old, int r, int c){
int neighbors = 0;
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (i!=0 || j!=0){
if (isValidPosition(r + i, c + j)){
if(old[r + i][c + j])
{
neighbors++;
}
}
}
}
}
return neighbors;
}

As I can see, you basically have two choices:
apply finite bounds, that is, for the cells in the first and last columns and rows, you implement an additional check when counting the number of 'living' neighbours.
apply periodic bounds, that is, the cells on the leftmost column and the cells on the rightmost column are considered as neighbours. With the help of modular arithmetic, these cells don't need to be handled separately from others.

Related

I am converting some java code to C. Stuck at one line CharAt()

I am new. Trying to learn. I assume I am gonna have to create a charat() function myself. or is there a library function that I can look up that is similar (google seemed to indicate so)? Does boolean here function the same in c? I am just learning debugging. like debugging training wheels. I guess I will find out later anyway but thought Id ask. Answers that explain the why of this stuff is eternally more helpful in understanding the differences in the languages. plus I actually just like talking to other humans. even digital ones.
while (scan.hasNext())
{
r = scan.nextInt();
c = scan.nextInt();
star = new char[r + 2][c + 2];
used = new boolean[r + 2][c + 2];
for (int i = 1; i < r + 1; i++)
{
String str = scan.next();
for (int j = 1; j < c + 1; j++)
star[i][j] = str.charAt(j - 1);
}
#include <stdlib.h>
#include <stdbool.h>
int r = 0;
int c = 0;
char[][] star;
boolean[][] used;
void fill(int i , int j) {
if (i == 0 || i == r + 1 || j == 0 || j == c + 1)
return;
used[i][j] = true;
if (star[i + 1][j] == '-' && !used[i + 1][j])
fill (i + 1 , j);
if (star[i - 1][j] == '-' && !used[i - 1][j])
fill (i - 1 , j);
if (star[i][j + 1] == '-' && !used[i][j + 1])
fill (i , j + 1);
if (star[i][j - 1] == '-' && !used[i][j - 1])
fill (i , j - 1);
}
int main(void){
int caseNumber = 1;
scanf("%d", &r);
scanf("%d", &c);
star = new char[r+2][c+2];
used = new boolean[r+2][c+2];
for(int i = 1; j < c + 1; i++){
scanf("%s", &str);
}
count = 0;
for (int i = 1; i < r + 1; i++)
for (int j = 1; j < c + 1; j++)
{
if (star[i][j] == '-')
{
if (!used[i + 1][j] && !used[i - 1][j] && !used[i][j + 1] && !used[i][j - 1])
{
count++;
fill(i , j);
}
}
}
printf("Case" + caseNumber + ":" + count);
caseNumber++;
}
}
}

Is there a recursion that checks whether the matrix diagonally has a sequence of alphabetic letters

I got a homework assignment, I have to find a recursive function that gets a 2D matrix and the number of rows in a matrix and returns true / false If the diagonal of the matrix has a sequence of letters a b c,
Can not think of a solution
public static void main(String[] args) {
char[][] mat = new char[5][5];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++)
mat[i][j] = (char) (int) ((Math.random() * 26) + 'a');
}
for (int i=0 ; i <mat.length ; i++)
mat[i][i] = (char)('a' + i);
//mat[2][2] = 'b';
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println(isDiagonalLettersSequence(mat, mat.length));
}[Here are two examples that I hope will help me explain myself][1]
https://i.stack.imgur.com/Z6qmn.png
This is pretty simple. Just check on each iteration if the current value is equals to previous +1:
public static boolean isDiagonalHasSequence(char[][] matrix) {
return isDiagonalHasSequence(matrix, 0);
}
private static boolean isDiagonalHasSequence(char[][] matrix, int row) {
if (row > 0 && row < matrix.length) {
// check diagonal \
if (matrix[row][row] != matrix[row - 1][row - 1] + 1)
return false;
// check diagonal /
if (matrix[row][matrix.length - row - 1] != matrix[row - 1][matrix.length - row - 2] + 1)
return false;
}
return row == matrix.length || isDiagonalHasSequence(matrix, row + 1);
}
In the main function:
String[][] arr = { {"a","e","d"},
{"h","b","c"},
{"f","f","c"}};
if(diagonal(arr, 0).equals("abc"))
System.out.print("true");
And the global recursive function should be:
public static String diagonal(String[][] arr, int i) {
if(i == arr.length - 1)
return arr[i][i];
return arr[i][i] + diagonal(arr, i + 1);
}

Crossword algorithm for Android using Java [duplicate]

This question already has answers here:
Algorithm to generate a crossword [closed]
(13 answers)
Closed 6 years ago.
I am working on cross word algorithm to develop a word app. After doing a lot of googling or search on StackOverflow, I was able to reach this point. But yet I am not able to understand the right implementation for algorithm in Java. Below is the class I used.
public class Crosswords {
char[][] cross;
int rows;
int cols;
char[][] numberGrid;
boolean startword;
final char DEFAULT = ' ';
public Crosswords() {
rows = 50;
cols = 50;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length;i++){
for (int j = 0; j < cross[i].length;j++){
cross[i][j] = DEFAULT;
}
}
}
public Crosswords(int ros, int colls) {
rows = ros;
cols = colls;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0;i < cross.length; i++){
for (int j = 0; j < cross[i].length; j++){
cross[i][j] = DEFAULT;
}
}
}
public String toString() {
String s = new String();
//String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
s = s + cross[i][j] + " ";
}
s = s + "\n";
}
return s;
}
public void addWordh(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > cols) {
System.out.println(s + " is longer than the grid. Please try another word.");
return;
}
if (c + s.length() > cols) {
System.out.println(s + " is too long. Please try another word.");
return;
}
if ((r - 2) >= 0) {
if ((cross[r - 1][c - 1 + s.length()] == DEFAULT) || (cross[r - 1][c - 1 + s.length()] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the beginning of another word!");
return;
}
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1][c - 1 + i] == DEFAULT) || (cross[r - 1][c - 1 + i] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= cols) && (c + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1][c - 1 + j] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1)][cols - 1 - (c - 1 + j)] = '*';
j++;
}
}
}
}
public void addWordv(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > rows) {
System.out.println(s + " is longer than the grid. Please try another word.");
}
if (r + s.length() > rows) {
System.out.println(s + " is too long. Please try another word.");
}
else {
if ((r - 2) >= 0) {
if ((cross[r - 2][c - 1] == DEFAULT) || (cross[r - 2][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
}
if ((cross[r - 1 + s.length()][c - 1] == DEFAULT) || (cross[r - 1 + s.length()][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1 + i][c - 1] == DEFAULT) || (cross[r - 1 + i][c - 1] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= rows) && (r + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1 + j][c - 1] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1 + j)][cols - 1 - (c - 1)] = '*';
j++;
}
}
}
}
}
public void setNumberGrid(){
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (cross[i][j] == DEFAULT){
numberGrid[i][j] = (char) 0;
}
else if (startword == true){
numberGrid[i][j] = (char) -2;
}
else {
numberGrid[i][j] = (char) -1;
}
}
int count = 1;
for (i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == -2){
numberGrid[i][j] = (char)count;
count++;
}
}
}
}
}
public String printNumberGrid() {
for (int i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == (char)-1){
numberGrid[i][j] = ' ';
}
else if (numberGrid[i][j] == (char)0){
numberGrid[i][j] = '#';
}
}
}
String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
d = d + numberGrid[i][j] + " ";
}
d = d + "\n";
}
return d;
}
public static void main(String[] args) {
Crosswords g = new Crosswords();
g.addWordv("rawr", 4, 5);
g.addWordh("bot", 5, 4);
g.addWordv("raw", 7, 5);
g.addWordh("cat", 4, 5);
g.addWordh("bass", 6, 10);
System.out.println(g);
Crosswords c = new Crosswords(20, 20);
c.addWordh("HELLO", 1, 1);
c.addWordv("HAPLOID", 1, 1);
c.addWordh("COMPUTER", 3, 12);
c.addWordv("CAT", 2, 11);
c.addWordv("WOAH", 2, 20);
c.addWordh("PARKING", 20, 5);
c.addWordv("ARK", 17, 6);
c.addWordh("AHOY", 6, 18);
c.addWordv("AHOY", 18, 10);
c.addWordv("ADVANTAGE", 2, 12);
c.addWordv("INTERNAL", 2, 18);
c.addWordh("BANTER", 7, 11);
c.addWordv("BEAGLE", 5, 12);
c.addWordh("BASE", 8, 3);
c.addWordv("BALL", 8, 3);
c.addWordh("LEFT", 10, 3);
c.addWordv("SAFE", 8, 5);
System.out.print(c);
}
}
As you can see in Main method that i am adding the words but also giving the row and column number to place the words like c.addWordv("Safe",8,5); where 8 and 5 is column number.
Now Question is how can i implement cross word algorithm which just take words and place them on board randomly without taking the row and column numbers.
Thanks in advance
EDIT:
I want to modify this class algo the way that i dont have to give away the rows and columns number..
//Pseudo Code
If the crossword size is maxSize and any word's length is stored in wordLength ,then you can use random method as below
int maxSize=20;
int wordLength=4;
Random random =new Random();
int r,c;
//for horizontal
r=random.nextInt(maxSize-wordLength);
c=random.nextInt(maxSize);
//for vertical
r=random.nextInt(maxSize);
c=random.nextInt(maxSize-wordLength);
You can store the row and column and generate the new one if its already present.

Having an issue with my file reader for Game of Life program

package edu.bsu.cs121.mamurphy;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
// Maurice Murphy
// CS121
// 10/17/15
public class GameOfLifeMain extends JFrame {
// Intitial reading and printing of the world
public GameOfLifeMain() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
Test test1 = new Test();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
public static void main(String[] asd) {
new GameOfLifeMain();
System.out.println();
}
}
class Temp extends Thread {
Test anim;
public Temp(Test anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
class Test extends JPanel
{
final static int numOfRow = 25, numOfCol = 75;
final static char DOT = '.';
static char[][] grid = new char[numOfRow + 2][numOfCol + 2];
static char[][] nextgrid = new char[numOfRow + 2][numOfCol + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 0; numOfRow <= numOfRow + 1; numOfRow++) {
for (int numOfCol = 0; numOfCol <= numOfCol + 1; numOfCol++) {
grid[numOfRow][numOfCol] = DOT;
nextgrid[numOfRow][numOfCol] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
String s = world.next();
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
grid[numOfRow][numOfCol] = s.charAt(numOfCol - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
x = 20;
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
g.drawString("" + grid[numOfRow][numOfCol], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int numOfRow = r - 1; numOfRow <= r + 1; numOfRow++) {
for (int numOfCol = c - 1; numOfCol <= c + 1; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int numOfRow = 1; numOfRow <= numOfRow; numOfRow++) {
for (int numOfCol = 1; numOfCol <= numOfCol; numOfCol++) {
if (grid[numOfRow][numOfCol] == 'X') {
int count = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count = count + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[numOfRow][numOfCol] = 'X';
} else
nextgrid[numOfRow][numOfCol] = DOT;
}
if (grid[numOfRow][numOfCol] == DOT) {
int count1 = 0;
{
if (grid[numOfRow][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow - 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol - 1] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol] == 'X')
count1 = count1 + 1;
if (grid[numOfRow + 1][numOfCol + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[numOfRow][numOfCol] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < numOfRow + 1; i++) {
for (int j = 0; j < numOfCol + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);// or whatever method you use to print the world
} else {
if (sameFlag == true) {
g.drawString("The worlds are repeating!", 10, 250);
}
if (blankFlag == true) {
g.drawString("The world is blank!", 10, 250);
}
}
}
}
Sorry about not putting in all the code.
Any help is greatly appreciated.
I have figured out the issue thanks to the help of all your answers. For whatever reason, Eclipse wasn't reading that the files were in the folder with the project, so I simply deleted and readded the files (in the same place mind you) and all of a sudden it started working again.
Now my current issue is to figure out why my program isn't proceeding onto the next generation of life.
Specifically, I need to be able to ask the user if they want to continue onto the next generation of life.
The output should be Do you want to go to the next generation? Type y for yes, type n to quit the program.
Part of your problem is that you are catching a general Exception, so anything could be going wrong. You should print the stack trace from your Exception to help in debugging this issue, as it will give you more precise info on where the error actually is. I.e., is it in opening the File or is it in creating a Scanner from the open File. Hopefully you are seeing why should not catch general exceptions.
Note this is only for debugging, though, as printing the stack trace is not good general practice.
File must located in directory project.
You see error message replace your source:
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
you probably need to provide the full path of the file. meaning the exact location of where the file is on your system.
also, it would be easier to have the file as a resource in your project. this way, you can easily load it as a resource by name as
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.txt");

Writing a Java program to run with a pre-built interface (the Life game) but I'm having trouble

Here's my code: http://pastebin.com/umy0FPvB (LG)
and here's the teacher's code: http://pastebin.com/y5wU0Zpx (LCI)
It's telling me I'm wrong on line 41 of the teacher's code when the LCI is trying to read from the matrix passed from the LG [world()].
I've been sitting on this for a while but I can't seem to figure out what's wrong.
Exception in thread "main" java.lang.NullPointerException
at Console.printWorld(Console.java:41)
at Console.playLife(Console.java:56)
at Console.main(Console.java:30)
--
/**
* The Life game
* #author Noah Kissinger
* #date 2012.2.13
*/
import java.util.Random;
public class Life {
private static boolean[][] matrix;
private static int bL, bH, lL, lH, r, c;
private static long rSeed;
public Life(long seed, int rows, int columns, int birthLow, int birthHigh,
int liveLow, int liveHigh) {
rSeed = seed;
bL = birthLow;
bH = birthHigh;
lL = liveLow;
lH = liveHigh;
r = rows;
c = columns;
createMatrix();
}
public void update() {
updateMatrix();
}
public boolean[][] world() {
return matrix;
}
public static void createMatrix() {
Random seedBool = new Random(rSeed);
boolean[][] matrix = new boolean[r][c];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = false;
}
}
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
matrix[i][j] = seedBool.nextBoolean();
}
}
}
public static void updateMatrix() {
Random seedBool = new Random(rSeed);
boolean[][] matrixCopy = matrix.clone();
for (int i = 0; i < matrix.length; i++)
matrixCopy[i] = matrix[i].clone();
int count = 0;
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
if (matrix[i][j] == false) {
if (matrixCopy[i - 1][j - 1] == true)
count++;
if (matrixCopy[i - 1][j] == true)
count++;
if (matrixCopy[i - 1][j + 1] == true)
count++;
if (matrixCopy[i][j - 1] == true)
count++;
if (matrixCopy[i][j + 1] == true)
count++;
if (matrixCopy[i + 1][j - 1] == true)
count++;
if (matrixCopy[i + 1][j] == true)
count++;
if (matrixCopy[i + 1][j + 1] == true)
count++;
if (count >= bL && count <= bH) {
matrix[i][j] = true;
for (int i1 = 0; i1 < matrix.length; i1++) {
for (int j1 = 0; j1 < matrix[i1].length; j1++) {
matrix[i1][j1] = false;
}
}
for (int i1 = 1; i1 < matrix.length - 1; i1++) {
for (int j1 = 1; j1 < matrix[i1].length - 1; j1++) {
matrix[i1][j1] = seedBool.nextBoolean();
}
}
} else
matrix[i][j] = false;
count = 0;
}
else {
if (matrixCopy[i - 1][j - 1] == true)
count++;
if (matrixCopy[i - 1][j] == true)
count++;
if (matrixCopy[i - 1][j + 1] == true)
count++;
if (matrixCopy[i][j - 1] == true)
count++;
if (matrixCopy[i][j + 1] == true)
count++;
if (matrixCopy[i + 1][j - 1] == true)
count++;
if (matrixCopy[i + 1][j] == true)
count++;
if (matrixCopy[i + 1][j + 1] == true)
count++;
if (count >= lL && count <= lH)
matrix[i][j] = true;
else
matrix[i][j] = false;
count = 0;
}
}
}
}
}
--
/**
* The Console class is a console interface to the Life game.
* #author DH
* #date Sept. 2008
*/
import java.util.Scanner;
public class Console {
/**
* #param args unused
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the size of the matrix(rows, columns) :");
int rows = in.nextInt();
int columns = in.nextInt();
System.out.println("Please enter random seed: ");
long seed = in.nextLong();
System.out.println("Please enter birth range (low, high) :");
int birthLow = in.nextInt();
int birthHigh = in.nextInt();
System.out.println("Please enter live range (low, high): ");
int liveLow = in.nextInt();
int liveHigh = in.nextInt();
try {
Life game = new Life(seed, rows, columns, birthLow, birthHigh, liveLow, liveHigh);
playLife(game);
} catch (IllegalArgumentException e) {
System.out.println("Inappropriate values: " + e.getMessage());
}
}
/**
* Print a boolean matrix
* #param world is a boolean matrix to be printed with # for true and - for false.
*/
public static void printWorld(boolean[][] matrix) {
for (int r=0; r<matrix.length; r++) {
for (int c=0; c<matrix[0].length; c++) {
System.out.print(matrix[r][c] ? " # " : " - ");
}
System.out.println();
}
System.out.println();
}
/**
* Play the game of Life starting with a given state
* #param game is the Life object that provides the current state of Life
*/
public static void playLife(Life game) {
printWorld(game.world());
for (int i=0; i<10; i++) {
game.update();
printWorld(game.world());
}
}
}
Here's your problem. In your createMatrix() method you define a local variable matrix when you really want to modify the field matrix.
You may find it useful to access fields with this, e.g. this.matrix. It makes a clear distinction in the code. However, most IDEs will auto highlight fields and local variables so some people find it unnecessary, it's a question of style and not overly important.
I haven't checked the rest of your program, there may be other errors.
public static void createMatrix() {
Random seedBool = new Random(rSeed);
this.matrix = new boolean[r][c];
for (int i = 0; i < this.matrix.length; i++) {
for (int j = 0; j < this.matrix[i].length; j++) {
this.matrix[i][j] = false;
}
}
for (int i = 1; i < this.matrix.length - 1; i++) {
for (int j = 1; j < this.matrix[i].length - 1; j++) {
this.matrix[i][j] = seedBool.nextBoolean();
}
}
}
boolean[][] matrix = new boolean[r][c];
This line creates a 2-dimensional array of boolean and stores it in a loca variable in the createMatrix method.
So, the static field matrix in the Life class still be null.
This field is read and passed through the world method into the playLife method.
And, next, the call of printLife method trigger NPE.
BTW, why did you implemented the game of life using many static fields and methods?

Categories

Resources