I have been working on a versions of Conway's Game of Life for school and I have run into a problem: cells are becoming dead or alive in the wrong places.
How can I fix that?
if (alive == 3 && aryBOARD[x][y] == 0) { //rule 4
aryCHANGE[x][y] = 1;
}
if (alive > 3 && aryBOARD[x][y] == 1) { //rule 3
aryCHANGE[x][y] = 0;
}
if (alive >= 2 && alive <= 3 && aryBOARD[x][y] == 1) { //rule 2
aryCHANGE[x][y] = 1;
}
if (alive < 2 && aryBOARD[x][y] == 1) { //rule 1
aryCHANGE[x][y] = 0;
}
if (dead > 5) { //rule check
aryCHANGE[x][y] = 0;
}
That is where I assume the problem is but if having the whole code would help:
package gameoflife2;
public class Game {
public static void main(String[] args) {
int[][] aryBOARD = new int[5][5];
int x = 0;
int y = 0;
int dead = 0;
int alive = 0;
int i, j;
// Board numbers
// 00011
// 00001
// 01000
// 01100
// 00000
aryBOARD[0][0] = 0;
aryBOARD[0][1] = 0;
aryBOARD[0][2] = 0;
aryBOARD[0][3] = 1;
aryBOARD[0][4] = 1;
aryBOARD[1][0] = 0;
aryBOARD[1][1] = 0;
aryBOARD[1][2] = 0;
aryBOARD[1][3] = 0;
aryBOARD[1][4] = 1;
aryBOARD[2][0] = 0;
aryBOARD[2][1] = 1;
aryBOARD[2][2] = 0;
aryBOARD[2][3] = 0;
aryBOARD[2][4] = 0;
aryBOARD[3][0] = 0;
aryBOARD[3][1] = 1;
aryBOARD[3][2] = 1;
aryBOARD[3][3] = 0;
aryBOARD[3][4] = 0;
aryBOARD[4][0] = 0;
aryBOARD[4][1] = 0;
aryBOARD[4][2] = 0;
aryBOARD[4][3] = 0;
aryBOARD[4][4] = 0;
// end of array
int[][] aryCHANGE = aryBOARD.clone(); // array change is equal to array
// board
// printing array
int rows = 5;
int colums = 5;
for (i = 0; i < rows; i++) {
for (j = 0; j < colums; j++) {
System.out.print(aryBOARD[i][j] + " ");
}
System.out.println("");
}
System.out.println("---------------------------");
// done printing array
// check for dead or alive cells
for (x = 0; x <= 4; x++) {
for (y = 0; y <= 4; y++) {
alive = 0;
dead = 0;
if ((x + 1 < 4) && (x + 1 > 0)) { // right
if (aryBOARD[x + 1][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y - 1 < 4) && (y - 1 > 0) && (x + 1 < 4) && (x + 1 > 0))) { // bottom
// right
// corner
if (aryBOARD[x + 1][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
if (((y + 1 < 4) && (y + 1 > 0) && (x + 1 < 4) && (x + 1 > 0))) { // top
// right
// corner
if (aryBOARD[x + 1][y + 1] == 0) {
dead++;
} else {
alive++;
}
}
if ((y + 1 < 4) && (y + 1 > 0)) {// top middle
if (aryBOARD[x][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y + 1 < 4) && (y + 1 > 0) && (x - 1 < 4) && (x - 1 > 0))) {// top
// left
// corner
if (aryBOARD[x - 1][y + 1] == 0) {
dead++;
} else {
alive++;
}
}
if ((x - 1 < 4) && (x - 1 > 0)) {// left
if (aryBOARD[x - 1][y] == 0) {
dead++;
} else {
alive++;
}
}
if (((y - 1 < 4) && (y - 1 > 0) && (x - 1 < 4) && (x - 1 > 0))) {// bottom
// left
// corner
if (aryBOARD[x - 1][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
// x++
if ((y - 1 < 4) && (y - 1 > 0)) {// bottom middle
if (aryBOARD[x][y - 1] == 0) {
dead++;
} else {
alive++;
}
}
// RULES
// 1 Any live cell with fewer than two live neighbors dies, as if caused
// by under-population.
// 2 Any live cell with two or three live neighbors lives on to the next
// generation.
// 3 Any live cell with more than three live neighbors dies, as if by
// overcrowding.
// 4 Any dead cell with exactly three live neighbors becomes a live
// cell, as if by reproduction.
// test alive and dead
if (alive == 3 && aryBOARD[x][y] == 0) {// rule 4
aryCHANGE[x][y] = 1;
}
if (alive > 3 && aryBOARD[x][y] == 1) {// rule 3
aryCHANGE[x][y] = 0;
}
if (alive >= 2 && alive <= 3 && aryBOARD[x][y] == 1) {// rule 2
aryCHANGE[x][y] = 1;
}
if (alive < 2 && aryBOARD[x][y] == 1) {// rule 1
aryCHANGE[x][y] = 0;
}
if (dead > 5) {// rule check
aryCHANGE[x][y] = 0;
}
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < colums; j++) {
System.out.print(aryCHANGE[i][j] + " ");
}
System.out.println("");
}
System.out.println("---------------------------");
} // end main
} // end class
You need to think a lot more about structuring your code and breaking things up into smaller chunks. That will help you a lot, especially when you move onto larger projects in the future.
For example write a simple method to count the number of living cells around a given cell.
Now your main loop through just becomes:
for (int x=0;x<width;x++) {
for (int y=0;y<height;y++) {
switch(countLivingAround(x,y)) {
case 0: // Less than 2 always dies
case 1:
grid(x,y) = 0;
break;
case 2: // Do nothing, keep current state
break;
case 3: // Breed
grid(x,y) = 1;
break;
case 4: // Dies from overcrowding
grid(x,y) = 0;
break;
}
}
}
Your count function can be simple, it just adds up the values at [x-1,y],[x,y+1], etc, remember to check for the edges of the board and handle that case correctly though.
In addition to breaking the logic up into different methods you need to either use a debugger to step thru the code or use printlns to display the x and y values your evaluating (See the sample below) You'll see that some of your calculations on the adjoining cells x and y coordinates need work.
for (x = 0; x <= 4; x++) {
for (y = 0; y <= 4; y++) {
alive = 0;
dead = 0;
System.out.println("evaluating cell x=" + x + ", y = " + y);
if ((x + 1 < 4) && (x + 1 > 0)) {// right
if (aryBOARD[x + 1][y] == 0) {
dead++;
}
else {
alive++;
}
System.out.println(" check 1 x=" + (x + 1) + ", y = " + y);
}
Related
Currently I'm trying to implement heuristics for a 3D tic-tac-toe but it seems like my counter is way of it,f but I'm unsure where I've done wrong, I'm not gonna post all of the code since it's a lot, but here is a part:
public void countDiagonal(GameState gameState) {
/*
* yz-plane (negativ)
*/
int z;
for (int x = 0; x < GameState.BOARD_SIZE; x++) {
for (int y = 0; y < GameState.BOARD_SIZE; y++) {
z = y;
if (gameState.at(x, y, z) == myPlayer) {
myCounter++;
opponentCounter = 0;
}
if (gameState.at(x, y, z) == opponentPlayer) {
opponentCounter++;
myCounter = 0;
}
if (gameState.at(x, y, z) == Constants.CELL_EMPTY) {
emptyCells++;
}
}
evaluateBoard();
myCounter = 0;
opponentCounter = 0;
emptyCells = 0;
}
The evaluation is done here:
public void evaluateBoard() {
if (myCounter == 1 && emptyCells == 3) {
myScore = myScore + 5;
}
if (myCounter == 2 && emptyCells == 2) {
myScore = myScore + 10;
}
if (myCounter == 3 && emptyCells == 1) {
myScore = myScore + 20;
}
if (myCounter == 4) {
myScore = myScore + 1000;
}
if (opponentCounter == 1 && emptyCells == 3) {
opponentScore = opponentScore + 5;
}
if (opponentCounter == 2 && emptyCells == 2) {
opponentScore = opponentScore + 10;
}
if (opponentCounter == 3 && emptyCells == 1) {
opponentScore = opponentScore + 20;
}
if (opponentCounter == 4) {
opponentScore = opponentScore + 1000;
}
}
When I try to run it, I use alpha-beta prune, but it seems like the calculation are done horrbly wrong, when I use the value, I take myScore - opponentScore and I use an alpha-beta tree with depth 1, but even after only playing one move, I'm down -15 in points, as I'm a noob in java, im therefore asking for help, is there an obvious mistake in my way of trying to evaluate the board?
I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.
So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've coded an entire program to play Connect Four, but the algorithm for checking who has won (after each turn) isn't working and I don't know why. I keep getting a weird message when I compile it (exception ArrayIndexOutOfBoundsException). Any help is appreciated.
Here is the code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class connectFourDemo extends Applet
implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
int[][] myGrid = new int[7][6];
// If piece is 0, white. If 1, red. If 2, black.
int xCoord, yCoord; // X and Y co-ordinates for mouse navigation.
int width, height;
int playerTurn = 1; // Player's turn. Default is 1 since red goes first.
int mx, my; // The mouse coordinates.
boolean isButtonPressed = false;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground(Color.yellow);
mx = width / 2;
my = height / 2;
addMouseListener(this);
addMouseMotionListener(this);
}
private int getXValue(int xValue) {
if (xValue < width / 7) return 0;
else if (xValue < width / 7 * 2) return 1;
else if (xValue < width / 7 * 3) return 2;
else if (xValue < width / 7 * 4) return 3;
else if (xValue < width / 7 * 5) return 4;
else if (xValue < width / 7 * 6) return 5;
else return 6;
}
private int getYValue(int yValue) {
if (yValue < width / 6) return 0;
else if (yValue < width / 6 * 2) return 1;
else if (yValue < width / 6 * 3) return 2;
else if (yValue < width / 6 * 4) return 3;
else if (yValue < width / 6 * 5) return 4;
else return 5;
}
public void verticalCheck(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 5; i >= 0; i--) {
if (myGrid[xCoord][i] == 1) {
System.out.println("Counter one in vertical check is " + counter + ".");
if (myGrid[xCoord][i - 1] == 1 && (i - 1 >= 0)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four vertically!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 5; i >= 0; i--) {
if (myGrid[xCoord][i] == 2) {
System.out.println("Counter two in vertical check is " + counter + ".");
if (myGrid[xCoord][i - 1] == 2 && (i - 1 >= 0)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four vertically!");
}
}
}
public void horizontalCheck(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
if (myGrid[i][y] == 1) {
System.out.println("Counter one in horizontal check is " + counter + ".");
if (myGrid[i + 1][y] == 1 && (i + 1 <= 6)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four horizontally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
if (myGrid[i][y] == 2) {
System.out.println("Counter two in horizontal check is " + counter + ".");
if (myGrid[i + 1][y] == 2 && (i + 1 <= 6)) counter++;
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four horizontally!");
}
}
}
public void diagonalCheckRight(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i <= 6; i++) {
for (int j = 5; j >= 0; j--) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four diagonally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 2) {
System.out.println("Counter two in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four diagonally!");
}
}
}
public void diagonalCheckLeft(int x, int y) {
if (myGrid[x][y] == 1) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check left is " + counter + ".");
if (myGrid[i - 1][j - 1] == 1 && (i + 1 <= 6) && (j - 1 >= 0)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 1 has won Connect Four diagonally!");
}
}
else if (myGrid[x][y] == 2) {
int counter = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (myGrid[i][j] == 2) {
System.out.println("Counter one in diagonal check left is " + counter + ".");
if (myGrid[i - 1][j - 1] == 2 && (i <= 6) && (j >= 0)) counter++;
}
}
}
if (counter == 4) {
System.out.println("Player 2 has won Connect Four diagonally!");
}
}
}
public void mouseEntered( MouseEvent e ) {
// Called when the pointer enters the applet's rectangular area.
}
public void mouseExited( MouseEvent e ) {
// Called when the pointer leaves the applet's rectangular area.
}
public void mouseClicked( MouseEvent e ) {
// Called after a press and release of a mouse button with no motion in between.
mx = e.getX();
my = e.getY();
xCoord = getXValue(mx);
yCoord = getYValue(my);
if (myGrid[xCoord][yCoord] == 0 && playerTurn == 1) { // Drop from top, fall to bottom and vice versa.
for (int y = 5; y >= yCoord; y--) {
if (myGrid[xCoord][y] == 0) {
myGrid[xCoord][y] = 1;
y = yCoord - 1;
}
}
verticalCheck(xCoord, yCoord);
horizontalCheck(xCoord, yCoord);
diagonalCheckRight(xCoord, yCoord);
diagonalCheckLeft(xCoord, yCoord);
playerTurn = 2;
}
else if (myGrid[xCoord][yCoord] == 0 && playerTurn == 2) {
for (int y = 5; y >= yCoord; y--) {
if (myGrid[xCoord][y] == 0) {
myGrid[xCoord][y] = 2;
y = yCoord - 1;
}
}
verticalCheck(xCoord, yCoord);
horizontalCheck(xCoord, yCoord);
diagonalCheckRight(xCoord, yCoord);
diagonalCheckLeft(xCoord, yCoord);
playerTurn = 1;
}
}
public void mousePressed(MouseEvent e) { // Called after a button is pressed down.
repaint();
// "Consume" the event so it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
public void mouseReleased(MouseEvent e) { // Called after a button is released.
repaint();
e.consume();
}
public void mouseMoved(MouseEvent e) { // Called during motion when no buttons are down.
mx = e.getX();
my = e.getY();
mx = mx / 50; // Divides applet width by the width of each oval (50).
my = my / 50; // Divides applet height by the height of each oval (50).
showStatus("Mouse in column " + (mx + 1) + ", row " + (my + 1) + ".");
}
public void mouseDragged(MouseEvent e) { // Called during motion with buttons down.
}
public void paint(Graphics g) {
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
if (myGrid[x][y] == 0) {
g.setColor(Color.white);
}
if (myGrid[x][y] == 1) {
g.setColor(Color.red);
}
if (myGrid[x][y] == 2) {
g.setColor(Color.black);
}
g.fillOval((width / 7) * x + 2, (height / 6) * y + 1, (width / 7) - 4, (height / 6) - 4);
}
}
}
}
Ran the code, your problem is in "diagonalCheckRight", namely this section:
for (int i = 0; i <= 6; i++) {
for (int j = 5; j >= 0; j--) {
if (myGrid[i][j] == 1) {
System.out.println("Counter one in diagonal check right is " + counter + ".");
if (myGrid[i + 1][j + 1] == 1 && (i + 1 <= 6) && (j + 1 <= 5)) counter++;
else if (myGrid[i - 1][j + 1] == 1 && (i - 1 >= 0) && (j + 1 <= 5)) counter++;
}
}
}
Your j index starts at 5, in the if you do myGrid[i+1][j+1] so that means on the first iteration you're accessing myGrid[1][6], however you defined myGrid to be of size [7][6] and so you're out of bounds because the valid indices are: [0..6][0..5].
Also next time look at the error message, my console was showing:
java.lang.ArrayIndexOutOfBoundsException: 6
at Main.diagonalCheckRight(Main.java:134)
I renamed the class to Main, and that 134 is exactly the line number where I found the error.
I wonder if it is possible to have minimal code for this:
for (int x = 1; x < 10; x++){
/*I want to replace this condition with (x%number == 0)
instead of writing out condition for every number, but
it did not work with for (int number = 1; number <= 3; number++)
in (x%number == 0), as it prints out every x and number
*/
if ((x%1) == 0 && (x%2) == 0 & (x%3) == 0){
System.out.println(success!);
}
}
I think
x % a == 0 && x % b == 0 && x % c == 0
is equalent to
x % (a * b * c) == 0
UPDATE
Multiplication is incorrect, you need to use LCM: x % lcm(a, b, c)
Have a look :
for (int x = 1; x < 10; x++){
boolean flag = false;
for(int num = 1; num <= 3; num++){
if ((x%num) == 0 ){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
System.out.println(x + " success!");
}
}
OUTPUT :
6 success!
I know the code is looking a little horrified but will work for any value of x and num
This is what you'd need to make a comp sci professor happy:
for (int x = 1; x < 10; x++){
boolean success = true;
for (int number = 1; number <= 3; number++) {
if ((x % number) != 0) {
success = false;
}
}
if (success) {
System.out.println("success!");
}
}
although note: (x % 1) is always 0.
This is what you'd need to make me happy, according to my rule of "avoid nested loops":
for (int x = 1; x < 10; x++) {
if (testNumber(x))
System.out.println(x + " success!");
}
}
private static boolean testNumber(int x) {
for (int number = 1; number <= 3; number++) {
if ((x % number) != 0) {
return false;
}
}
return true;
}