First time posting, have a question about a table class I'm working on. For some reason adding a new row doesn't add the correct number of rows. I've added the code
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
These here are the methods I have to add a new row and column to the table. Below is what I'm using to test. For some reason it's adding a 5th row. Not sure where from.
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
Any help or ideas would be much appreciated, thanks!
Full Code:
public class Table<T> implements AbstractTable<T> {
List<List<T>> table;
public Table(Class<T> t) { table = new ArrayList<>(); }
public int rows() { return table.size(); }
public int cols() {
if(rows() == 0) {
return 0;
} else {
return table.get(0).size();
}
}
public T get(int i, int j) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).get(j);
}
public T set(int i, int j, T x) {
if (i < 0 || i > rows() - 1 || j < 0 || j > cols()-1)
throw new IndexOutOfBoundsException();
return table.get(i).set(j, x);
}
public void addRow(int i) {
if (i < 0 || i > rows()) throw new IndexOutOfBoundsException();
table.add(i, new ArrayList<T>());
for(int j = 0; j < cols(); j++) {
table.get(i).add(null);
}
}
public void addCol(int j) {
if (j < 0 || j > cols()) throw new IndexOutOfBoundsException();
if(rows() == 0) {
addRow(0);
}
for (int i = 0; i < rows(); i++) {
table.get(i).add(j, null);
}
}
public void removeRow(int i) {
if (i < 0 || i > rows() - 1) throw new IndexOutOfBoundsException();
table.remove(i);
}
public void removeCol(int j) {
if (j < 0 || j > cols() - 1) throw new IndexOutOfBoundsException();
for (int i = 0; i < rows(); i++) {
table.get(i).remove(j);
}
}
public static void main(String[] args) {
Table<Integer> table = new Table<>(Integer.class);
for(int i = 0; i < 4; i++) {
table.addCol(table.cols());
}
for(int i = 0; i < 4; i++) {
table.addRow(table.rows());
}
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
table.removeCol(1);
table.removeRow(1);
System.out.println("rows: " + table.rows() + "\ncols: " + table.cols());
}
}
If you used a debugger, you’d see that you are adding the extra row in addCol
Related
I have a 2D array (a matrix of 10x10) with values ranging from 0 to -5.
I want a method to be triggered when there is a sequence of a value found within the array.
For example, there is a sequence of two negative 2. I want it to trigger an event/method that will give a bonus score of 4. This should happen only when there are two -2's and not if there is just one -2.
I tried achieving something like that but I cant figure out how to tell the program to only trigger when 'n' number of a value is found within the matrix.
public class Test {
static int board[][] = new int[10][10];
public static void Test() {
int i, j;
board[0][0] = -1;
board[0][1] = -1;
board[1][1] = -2;
board[1][2] = -2;
board[1][3] = -2;
board[1][4] = -2;
for (i = 0; i < board.length; i++) {
System.out.println("");
for (j = 0; j < board.length; j++) {
//board[i][j] = 0;
System.out.print(board[i][j]);
}
}
System.out.println();
}
public static void scanBoard() {
int i, j;
for (i = 0; i < board.length; i++) {
for (j = 0; j < board.length; j++) {
if (board[i][j] == -1) {
System.out.println("Hello");
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(); //scans for
}
}
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 3 && j > 3) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && j > 5) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 3 < size)) {
if (matrix[i][j + 1] == -2 && matrix[i][j + 2] == -2 && matrix[i][j + 3] == -2) {
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
I am not sure if this is the result you wished to see according to your request. I hope this helps you. And I did some changes in your code so it will be easier to read (In my opinion lol).
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && (j == 0 || j == 1)) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 8 && (j == 5 || j == 6)) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 1 < size)) {
if (matrix[i][j + 1] == -2) {
//You can remove the '.toUpperCase()', it's just my personal preference
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
From what I understood from the problem statement and comments, you want your scanBoard to behave like this:
public static void scanBoard(int value, int frequency) {
int i, j;
if (value <= 0 && value >= -5 && frequency >= 2 && frequency <= 10) {
for (i = 0; i < board.length; i++) {
int rowFrequency = 0;
for (j = 1; j < board.length; j++) {
if (board[i][j] == value && board[i][j - 1] == value) {
rowFrequency++;
} else {
rowFrequency = 0;
}
if (rowFrequency + 1 >= frequency) {
System.out.println("Hello");
}
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(-2, 4); //prints Hello once
scanBoard(-2, 3); //prints Hello twice
scanBoard(-2, 3); //prints Hello thrice
}
I have written a program for an assignment where we had to write a simple Gomoku program. I thought I had it all, but when I compile and run, it sets off the win scenario even if I only have 4 of a kind and even if they're not next to each other. (It should only set off a win if there are five in a row of one kind...X's or O's). I feel like I should be resetting my counter back to 0 before each turn, but I'm not sure where I should be doing that. Any tips would be appreciated!
import java.util.Scanner;
public class Gomoku1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
char[][] map = new char [19][19];
int row = 0;
int column = 0;
//fill game with dots
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
map[i][j] = '.';
}
}
printMap(map);
char player1Choice = 'X';
char player2Choice = 'O';
int [] place;
while (true)
{
System.out.println("Player 1's turn!");
place = userTurn(map, player1Choice);
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player1Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player1Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player1Choice) == true)
{
System.out.println("Player 1 Wins!");
break;
}
else
{
System.out.println("Player 2's turn!: ");
place = userTurn(map, player2Choice);
//System.out.println(isValidMove(map, row, column));
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player2Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player2Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player2Choice) == true)
{
System.out.println("Player 2 Wins!");
break;
}
}
}
}
public static void printMap (char[][] map)
{
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
System.out.printf("%2c", map[i][j]);
}
System.out.println();
}
}
public static int [] userTurn (char[][] map, char playerChoice)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter row: ");
int row = input.nextInt();
System.out.print("Enter column: ");
int column = input.nextInt();
int place [] = {row, column};
return place;
}
public static boolean isValidMove (char[][] map, int row, int column)
{
//System.out.println ("n is valid move");
if (row < 0 || row > 18 || column < 0 || column > 18 || map[row][column]=='O' || map[row][column]=='X')
{
return false;
}
else
{
return true;
}
}
public static boolean isBoardFull (char[][] map)
{
int openSpots = 0;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (!(map[i][j]=='.'))
openSpots++;
}
}
if (openSpots == 361)
{
return true;
}
return false;
}
public static boolean hasPlayerWon(char[][] map, int player)
{
if (isHorizontalWin(map, player) == true || isVerticalWin(map, player) == true || isDiagonalWin(map, player) == true)
{
return true;
}
return false;
}
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isVerticalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 1;
c += 0;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isDiagonalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count++;
r += 1;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
}
You have problems in all three of the function that check win conditions: isHorizontalWin, isVerticalWin, and isDiagonalWin. All three increment the variable count, but this variable is never set back to zero. Additionally, the check to see if count == 5 should be made inside the loop. Here is an example on how to fix isHorizontalWin:
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
if (count == 5)
{
return true;
} else {
count = 0;
}
}
}
}
return false;
}
I'm trying to code a method which checks for duplicates on my Sudoku board. Currently, my method getFrontier() always returns true, and I've come to learn that it's because it's only checking for one value rather than an array or values. I use the method 3 times in squareCheck(), rowCheck() and columnCheck(). Is there any way to code the method so it would retain the previous value which was input and then check it against the new value?
My current code:
public class validCheck {
public boolean isSolved(int[][][] board)
{
for(int index = 0; index < board.length;index++)
{
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length;c++)
{
if(board[index][r][c] == 0)
return false;
}
}
}
return true;
}
public boolean getFrontier(int value)
{
Set<Integer> reserve = new HashSet<>();
for(int n = 1; n < 10; n++)
{
if(value == n && reserve.contains(n))
return false;
else if(value == n) reserve.add(n);
}
return true;
}
public boolean squareCheck(int[][][] board, int index)
{
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length; c++)
{
if(!getFrontier(board[index][r][c]))
{
System.out.println("Square error at ["+index + r + c +"]");
return false;
}
}
}
return true;
}
public boolean isValid(int[][][] board)
{
if(isSolved(board))
{
for(int i = 0; i < board.length; i++)
{
for(int r = 0; r < board[0].length;r++)
{
for(int c = 0; c < board[0].length;c++)
{
if(!rowCheck(board,i,r) || !columnCheck(board,i,c) || !squareCheck(board,i))
{
return false;
}
}
}
}
}
return true;
}
public boolean columnCheck(int[][][] board, int index, int col)
{
int target = 0;
if(index <=2)
{
target = index + 6;
}
else if(index > 2 && index < 6)
{
target = index +3;
index = index - 3;
}
else if (index > 5)
{
target = index;
index = index - 6;
}
while(index <= target)
{
for(int r = 0; r < board[0].length;r++)
{
if(!getFrontier(board[index][r][col]))
{
System.out.println("Column error at " + index + r + col);
return false;
}
}
index = index + 3;
}
return true;
}
public boolean rowCheck(int[][][] board, int index, int row)
{
int target = 0;
if(index <= 2)
{
index = 0;
target = 2;
}
else if (index <= 5)
{
index = 3;
target = 5;
}
else if(index <= 8)
{
index = 6;
target = 8;
}
while(index <= target)
{
for(int c = 0; c < board[0].length; c++)
{
if(!getFrontier(board[index][row][c]))
{
System.out.println("Row error at "+index+row+c);
return false;
}
}
index++;
}
return true;
}
}
Usage:
public static void main(String[] args) {
int[][][] solved = {{{5,3,4},{6,7,2},{1,9,8}},
{{6,7,8},{1,9,5},{3,4,2}},
{{9,1,2},{3,4,8},{5,6,7}},
{{8,5,9},{4,2,6},{7,1,3}},
{{7,6,1},{8,5,3},{9,2,4}},
{{4,2,3},{7,9,1},{8,5,6}},
{{9,6,1},{2,8,7},{3,4,5}},
{{5,3,7},{4,1,9},{2,8,6}},
{{2,8,4},{6,3,5},{1,7,9}}};
validCheck checker = new validCheck();
if(checker.isValid(solved))
System.out.println(true);
else System.out.println(false);
}
Any help will be greatly be appreciated!!!
Here is what I would do to find a valid board config in a 2D sudoku board. I would use a HashSet for a row and another for the column, as long as we never encounter repeats and the values contain 1 to the length of the array we know the board is valid.
int [][] board = {{1,2,3},
{2,3,1},
{3,1,2}
};
HashSet<Integer> rowDuplicates = new HashSet<>();
HashSet<Integer> colDuplicates = new HashSet<>();
boolean invalidBoard = false;
for(int i = 0 ; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
if(rowDuplicates.contains(board[i][j]) || colDuplicates.contains(board[j][i]))
{
//this board is not valid
invalidBoard = true;
}
else
{
rowDuplicates.add(board[i][j]);
colDuplicates.add(board[j][i]);
}
}
//now check they contain the correct numbers from 1 to the size of the array
if(colDuplicates.size() == rowDuplicates.size())
{
for(int index = 0; index < colDuplicates.size(); index++)
{
if(!(colDuplicates.contains(index + 1) && rowDuplicates.contains(index + 1)))
{
invalidBoard = true;
break;
}
}
}
else
{
invalidBoard = true;
}
colDuplicates.clear();
rowDuplicates.clear();
}
System.out.println("invalid board: " + invalidBoard);
You should be able to expand this to your 3D array but you can see how much easier it is to use HashSets to verify a valid 2D array Sudoku board.
Like many other person as I see, I have a problem with my implementation of the Minmax algorithm for the game Connect4. In the example below, the algorithm doesn't try to block the player two and I don't understand why. My evaluation function is really basic: a binary function. Maybe it's because of the depth, but I don't think so.
Code:
public class Moteur {
public static void addPawn(int[][] game, int column, int player) {
int i = 0;
while (i < 6 && game[i][column] == 0) {
i++;
}
game[(i==6)?5:i-1][column] = player;
}
public static void kickPawn(int[][] game, int column) {
int i = 0;
while (i < 6 && game[i][column] == 0) {
i++;
}
game[i][column] = 0;
}
public static void AI_play(int[][] game, int depth) {
int max = -10000;
int tmp = 0;
int maxj = -5;
int j;
for (j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 1);
tmp = Min(game, depth - 1);
if (tmp > max) {
max = tmp;
maxj = j;
}
kickPawn(game, j);
}
}
addPawn(game, maxj, 1);
}
public static int Max(int[][] game, int depth) {
if(depth == 0 || winner(game) != 0) {
return eval(game);
}
int max = -10000;
int j, tmp;
for(j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 2);
tmp = Min(game, depth - 1);
if(tmp > max) {
max = tmp;
}
kickPawn(game, j);
}
}
return max;
}
public static int Min(int[][] game, int depth) {
if(depth == 0 || winner(game) != 0) {
return eval(game);
}
int min = 10000;
int j, tmp;
for(j = 0; j < 7; j++) {
if(game[0][j] == 0) {
addPawn(game, j, 1);
tmp = Max(game, depth - 1);
if(tmp < min) {
min = tmp;
}
kickPawn(game, j);
}
}
return min;
}
public static int eval(int[][] game) {
int gameWinner, nb_pawns = 0;
for (int i = 0; i < game.length; i++) {
for (int j = 0; j < game[0].length; j++) {
if(game[i][j] != 0) {
nb_pawns++;
}
}
}
gameWinner = winner(game);
if(gameWinner == 1) {
return 1000 - nb_pawns;
} else if (gameWinner == 2) {
return -1000 + nb_pawns;
} else {
return 0;
}
}
public static int winner(int[][] game) {
Integ e = new Integ();
for (int j = 0; j < game[0].length; j++) {
if(game[5][j]!= 0 && testWinner(game, j, e)) {
return e.getI();
}
}
return 0;
}
public static boolean testWinner(int[][] game, int lastColumn, Integ e) {
int lastRow = 0;
while (lastRow < 6 && game[lastRow][lastColumn] == 0) {
lastRow++;
}
lastRow = lastRow;
int i = 0;
int j = 0;
int currentPlayer = game[lastRow][lastColumn];
e.setI(currentPlayer);
int sequence = 0;
i = lastRow;
boolean b = i < 3
&& game[i][lastColumn] == currentPlayer
&& game[i+1][lastColumn] == currentPlayer
&& game[i+2][lastColumn] == currentPlayer
&& game[i+3][lastColumn] == currentPlayer;
if(b) {
return true;
}
sequence = 0;
j = lastColumn;
do {
j--;
} while(0 < j && game[lastRow][j] == currentPlayer);
if(j < 0 || game[lastRow][j] != currentPlayer) {
j++;
}
while(j <= 6 && game[lastRow][j] == currentPlayer) {
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i--;
j--;
} while(0 < i && 0 < j && game[i][j] == currentPlayer);
if(i < 0 || j < 0 || game[i][j] != currentPlayer) {
i++;
j++;
}
while(i <= 5 && j <= 6 && game[i][j] == currentPlayer) {
i++;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
sequence = 0;
i = lastRow;
j = lastColumn;
do {
i++;
j--;
} while(i < 5 && 0 < j && game[i][j] == currentPlayer);
if (5 < i || j < 0 || game[i][j] != currentPlayer) {
i--;
j++;
}
while(0 <= i && j <= 6 && game[i][j] == currentPlayer) {
i--;
j++;
sequence++;
}
if (sequence >= 4) {
return true;
}
return false;
}
public static void main(String[] args) {
int[][] game = new int[6][7];
int depth = 5;
game[5][3] = 2;
game[4][3] = 2;
game[3][3] = 2;
AI_play(game, depth);
//game[4][0] = 2;
//AI_play(game, depth);
//game[5][2] = 2;
//AI_play(game, depth);
//game[5][3] = 2;
//AI_play(game, depth);
//game[1][0] = 2;
//AI_play(game, depth);
//game[5][4] = 2;
//AI_play(game, depth);
for (int i = 0; i < game.length; i++) {
for (int j = 0; j < game[0].length; j++) {
System.out.print(game[i][j]);
}
System.out.println("");
}
}
private static class Integ {
private int i;
public Integ() {
this.i = 0;
}
public void increment() {
this.i = this.i + 1;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was trying to solve the Game of life problem for a teacher. Rules of that game are:
Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors’ lives on to the next generation. Any live cell with more than three live neighbors dies, as if by overcrowding. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
There are two problems with my code - first of all, my main class doesn't seem to be working. Secondly, I performed the problem through many many if else statements. Are there more concise ways of writing the exceptions for my getNeighbors() method?
Thanks!
import java.util.Random;
public class GameOfLife {
final static int ROWS = 6;
final static int COLUMNS = 7;
String[][] simulator;
private Random randomGenerator;
public GameOfLife() {
simulator = new String[ROWS][COLUMNS];
randomGenerator = new Random();
}
public void fillSpot (int row, int column) {
simulator [row][column] = "O";
}
private void deleteSpot (int row, int column) {
simulator[row][column] = "";
}
// Do I need the above methods? really?
public void randomSimulation() {
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
int random = randomGenerator.nextInt(1);
if (random == 1) {
fillSpot(i,j);
}
}
}
}
private void getNeighbors (int row, int column) {
int neighbors = 0;
if (row < ROWS && row > 0 && column < COLUMNS && column > 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
if (row > ROWS || column > COLUMNS || row < 0 || column < 0) {
}
else if (row == ROWS && column < COLUMNS && column != 0) {
for (int i = row - 1; i <= ROWS; i++) {
for (int j = column - 1; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row < ROWS && column == COLUMNS && row != 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column - 1; j <= COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row == 0 && column < COLUMNS && column != 0) {
for (int i = 0; i <= row + 1; i++) {
for (int j = column - 1; j <= COLUMNS + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (row == 0 && column == COLUMNS) {
for (int i = row; i <= row + 1; i++) {
for (int j = column - 1; j <=COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else if (column == 0 && row < ROWS && row != 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = column; j <= COLUMNS + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
else {
for (int i = row; i <= row + 1; i++) {
for (int j = column; j <= column + 1; j++) {
String temp = simulator[i][j];
if (temp.contains("O")) {
neighbors++;
}
}
}
}
// for row == 0 && column == 0
if (simulator [row][column].contains("O")) {
neighbors--;
}
simulator[row][column] += " " + neighbors;
}
//There are wayyy too manyy clauses here for me to be comfortable. There's got to be a way to do this cleaner
private void nextGenPlanning() {
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
getNeighbors(i,j);
}
}
}
private void nextGen() {
nextGenPlanning();
for (int i = 0; i <= ROWS; i++) {
for (int j = 0; j <= COLUMNS; j++) {
String temp = simulator[i][j];
if (temp.charAt(temp.length()) <= 1 || temp.charAt(temp.length()) >= 4) {
deleteSpot(i,j);
}
else {
fillSpot (i,j);
}
}
}
}
public String toString() {
String string = "";
for (int i = 0; i < ROWS; i++) {
string = string + "|";
for (int j = 0; j < COLUMNS; j++) {
String temp = simulator[i][j];
string = string + temp.charAt(0);
}
string = string + "|\n";
}
return string;
}
public String simulate (int numOfTrials) {
String string = "";
for (int i = 0; i <= numOfTrials; i++) {
nextGen();
string += toString();
}
return string;
}
public void main (String [] args) {
randomSimulation();
System.out.println(simulate(2));
}
}
First, you have:
public void main (String [] args) {
randomSimulation();
System.out.println(simulate(2));
}
You should have:
public static void main (String[] args) {
GameOfLife game = new GameOfLife();
game.randomSimulation();
System.out.println(game.simulate(2));
}
Second, for getNeighbors, first consider that a 'get' method usually returns a value. If you're counting the number of neighbors, consider:
public int getNeighbors(int x, int y) {
int neighbors = 0;
int leftX = Math.max(x-1, 0);
int rightX = Math.min(x+1, COLUMNS);
int topY = Math.max(y-1, 0);
int bottomY = Math.min(y+1, ROWS);
for (int i=leftX; i < rightX; i++) {
for (int j=topY; j < bottomY; j++) {
if (simulator[i][j].contains('O')) { // Notice I'm using a char here, see my next comment
neighbors++;
}
}
}
return neighbors;
}
Third, I recommend using char[][] instead of String[][] for your simulator if each space in the simulator only holds one character value. There are some things about Strings in Java that you don't need to get tripped up with - for example, in Java, you cannot compare the value of Strings using == (you need to use String's equals() method).
First , your main class should be Public static void main(String[] args) and you can use switch case except of if else if you really sure on if else you can use if ( blabla == blablabla &(this means and ) blaba == babalaba)