Cant run the code, intelij run arrow is 'grey' [duplicate] - java

This question already has answers here:
Auto errors detection in IntelliJ IDEA
(8 answers)
Closed 5 years ago.
enter image description here import java.util.Scanner;
public class EnglishCheckers {
// Global constants
public static final int RED = 1;
public static final int BLUE = -1;
public static final int EMPTY = 0;
public static final int SIZE = 8;
// You can ignore these constants
public static final int MARK = 3;
public static EnglishCheckersGUI grid;
public static Scanner getPlayerFullMoveScanner = null;
public static Scanner getStrategyScanner = null;
public static final int RANDOM = 1;
public static final int DEFENSIVE = 2;
public static final int SIDES = 3;
public static final int CUSTOM = 4;
public static void main(String[] args) {
// ******** Don't delete *********
// CREATE THE GRAPHICAL GRID
grid = new EnglishCheckersGUI(SIZE);
// *******************************
//showBoard(example);
//printMatrix(example);
//interactivePlay();
//twoPlayers();
/* ******** Don't delete ********* */
if (getPlayerFullMoveScanner != null){
getPlayerFullMoveScanner.close();
}
if (getStrategyScanner != null){
getStrategyScanner.close();
}
/* ******************************* */
}
public static int[][] createBoard() {
int[][] board = null;
board=new int[8][8]; // defines the new length of the array
for (int j=0; j<8; j=j+1)
{
for (int m=0; m<8; m=m+1) // these two "for" loops will set the value of each square of the board according to the instructions regarding it's location.
{
if (j==0|j==2)
{
if (m%2==0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j==1)
{
if (m%2!=0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j>2&j<5)
board[j][m]=0;
if (j==5|j==7)
{
if (m%2!=0)
board[j][m]=-1;
else
board[j][m]=0;
}
if (j==6)
{
if (m%2==0)
board[j][m]=-1;
else
board[j][m]=0;
}
}
}
return board;
}
public static int howManyDiscs (int[][] board, int player){ // this function will return the number of discs a player has on the board
int positive=0;
int negative=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]>0) positive=positive+1;
if (board[i][j]<0) negative=negative+1;
}
}
if (player>0) return positive;
else return negative;
}
public static int[][] playerDiscs(int[][] board, int player) {
int[][] positions = null;
if (howManyDiscs(board,player)>0)
{
positions=new int[howManyDiscs(board,player)][2]; // defines the new length of the array
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (player>0&&board[i][j]>0) // will update the array if the player is 1
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
if (player<0&&board[i][j]<0) // will update the array if the player is (-1)
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
}
}
}
return positions;
}
public static boolean isBasicMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toCol==fromCol+1||toCol==fromCol-1) // checks if the destination column is legal
{
if (toRow==fromRow+1&&player!=-1) // makes sure the move is legal for a player that isn't (-1)
{
ans=true;
}
if (toRow==fromRow-1&&player!=1) // makes sure the move is legal for a player that isn't 1
{
ans=true;
}
}
}
}
}
return ans;
}
public static int[][] getAllBasicMoves(int[][] board, int player) {
int[][] moves = null;
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i+1,j-1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j-1)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // the if's below will insert every move that exists for each square to the array
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i+1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j-1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j-1;
line=line+1;
}
}
}
return moves;
}
public static boolean isBasicJumpValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toRow==fromRow+2)
{
if (toCol==fromCol+2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol+1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol+1]>0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol-1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol-1]>0)
ans=true;
}
}
}
if (toRow==fromRow-2)
{
if (toCol==fromCol+2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol+1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol+1]<0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol-1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol-1]<0)
ans=true;
}
}
}
}
}
}
return ans;
}
public static int [][] getRestrictedBasicJumps(int[][] board, int player, int row, int col) {
int[][] moves = null;
int line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicJumpValid(board,player,row,col,i,j)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2)
{
if (isBasicJumpValid(board,player,row,col,i,j)) // will insert every possible jump to the array
{
moves[line][0]=row;
moves[line][1]=col;
moves[line][2]=i;
moves[line][3]=j;
line=line+1;
}
}
}
return moves;
}
public static int[][] getAllBasicJumps(int[][] board, int player) {
int [][] moves = null;
int [][] discs = playerDiscs(board,player); // this array holds a list of the discs the player has on the board currently
int counter=0;
for (int i=0; i<discs.length; i=i+1) // will add each disc's amount of possible moves to the counter
counter=counter+getRestrictedBasicJumps(board,player,discs[i][0],discs[i][1]).length;
moves=new int[counter][4]; // defining the array's size according to the sum of all discs possible jumps
int line=0;
for (int a=0; a<discs.length; a=a+1)
{
int [][] jumps = getRestrictedBasicJumps(board,player,discs[a][0],discs[a][1]); // creates the array "jumps" that holds the possible jumps for the current "for" disc
for (int i=0; i<jumps.length; i=i+1) // will insert each line of the jumps array to the moves array
{
moves[line][0]=jumps[i][0];
moves[line][1]=jumps[i][1];
moves[line][2]=jumps[i][2];
moves[line][3]=jumps[i][3];
line=line+1;
}
}
return moves;
}
public static boolean canJump(int[][] board, int player) {
boolean ans = false;
if (getAllBasicJumps(board,player).length>0) ans=true;
return ans;
}
public static boolean isMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol))
ans=true;
else
if (isBasicMoveValid (board,player,fromRow,fromCol,toRow,toCol))
ans=true;
return ans;
}
public static boolean hasValidMoves(int[][] board, int player) {
boolean ans = false;
if (getAllBasicMoves(board,player).length>0) ans=true;
if (canJump(board,player)) ans=true;
return ans;
}
public static int[][] playMove(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol)) // in case it's a jump- will replace the eaten player with 0
{
if (fromRow>toRow)
{
if (fromCol>toCol) board[fromRow-1][fromCol-1]=0;
else board[fromRow-1][fromCol+1]=0;
}
else
{
if (fromCol>toCol) board[fromRow+1][fromCol-1]=0;
else board[fromRow+1][fromCol+1]=0;
}
}
if (player==1&toRow==7)
{
board[toRow][toCol]=2;
board[fromRow][fromCol]=0;
}
else
{
if (player==-1&toRow==0)
{
board[toRow][toCol]=-2;
board[fromRow][fromCol]=0;
}
else
{
board[toRow][toCol]=player;
board[fromRow][fromCol]=0;
}
}
return board;
}
public static boolean gameOver(int[][] board, int player) {
boolean ans = false;
if (!hasValidMoves(board,player)) ans=true;
if (playerDiscs(board,1)==null | playerDiscs(board,-1)==null) ans=true;
return ans;
}
public static int findTheLeader(int[][] board) {
int ans = 0;
int player1=0, player2=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]==1) player1=player1+1;
if (board[i][j]==2) player1=player1+2;
if (board[i][j]==-1) player1=player2+1;
if (board[i][j]==-2) player1=player2+2;
}
}
if (player1>player2)
ans=1;
else
if (player2>player1)
ans=-1;
else
ans=0;
return ans;
}
public static int[][] randomPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (getAllBasicMoves(board,player).length>0 && isMoveValid(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]))
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
else
if (getAllBasicJumps(board,player).length>0 && isMoveValid(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
}
return board;
}
public static int[][] defensivePlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
boolean goodMove=false;
int i=0;
int [][] arr=board;
while (i<getAllBasicMoves(board,player).length && !goodMove)
{
arr=playMove(board,player,getAllBasicMoves(board,player)[i][0],getAllBasicMoves(board,player)[i][1],getAllBasicMoves(board,player)[i][2],getAllBasicMoves(board,player)[i][3]);
if (!canJump(arr,-player))
goodMove=true;
i=i+1;
}
board=arr;
}
}
return board;
}
public static int[][] sidesPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
if (getAllBasicMoves(board,player).length>1)
{
int bestMove=0, minHefresh=7;
for (int i=1; i<getAllBasicMoves(board,player).length; i=i+1)
{
if (Math.abs(0-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(0-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i-1][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i-1][3]);
}
}
board=playMove(board,player,getAllBasicMoves(board,player)[bestMove][0],getAllBasicMoves(board,player)[bestMove][1],getAllBasicMoves(board,player)[bestMove][2],getAllBasicMoves(board,player)[bestMove][3]);
}
else
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
}
}
return board;
}
//******************************************************************************//
/* ---------------------------------------------------------- *
* Play an interactive game between the computer and you *
* ---------------------------------------------------------- */
public static void interactivePlay() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the interactive Checkers Game !");
int strategy = getStrategyChoice();
System.out.println("You are the first player (RED discs)");
boolean oppGameOver = false;
while (!gameOver(board, RED) && !oppGameOver) {
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
EnglishCheckersGUI.sleep(200);
board = getStrategyFullMove(board, BLUE, strategy);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0){
winner = findTheLeader(board);
}
if (winner == RED) {
System.out.println();
System.out.println("\t *************************");
System.out.println("\t * You are the winner !! *");
System.out.println("\t *************************");
}
else if (winner == BLUE) {
System.out.println("\n======= You lost :( =======");
}
else
System.out.println("\n======= DRAW =======");
}
/* --------------------------------------------------------- *
* A game between two players *
* --------------------------------------------------------- */
public static void twoPlayers() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the 2-player Checkers Game !");
boolean oppGameOver = false;
while (!gameOver(board, RED) & !oppGameOver) {
System.out.println("\nRED's turn");
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
System.out.println("\nBLUE's turn");
board = getPlayerFullMove(board, BLUE);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0)
winner = findTheLeader(board);
System.out.println();
System.out.println("\t ************************************");
if (winner == RED)
System.out.println("\t * The red player is the winner !! *");
else if (winner == BLUE)
System.out.println("\t * The blue player is the winner !! *");
else
System.out.println("\t * DRAW !! *");
System.out.println("\t ************************************");
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a human player. *
* --------------------------------------------------------- */
public static int[][] getPlayerFullMove(int[][] board, int player) {
// Get first move/jump
int fromRow = -1, fromCol = -1, toRow = -1, toCol = -1;
boolean jumpingMove = canJump(board, player);
boolean badMove = true;
getPlayerFullMoveScanner = new Scanner(System.in);//I've modified it
while (badMove) {
if (player == 1){
System.out.println("Red, Please play:");
} else {
System.out.println("Blue, Please play:");
}
fromRow = getPlayerFullMoveScanner.nextInt();
fromCol = getPlayerFullMoveScanner.nextInt();
int[][] moves = jumpingMove ? getAllBasicJumps(board, player) : getAllBasicMoves(board, player);
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badMove)
System.out.println("\nThis is an illegal move");
}
// Apply move/jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
// Get extra jumps
if (jumpingMove) {
boolean longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
while (longMove) {
fromRow = toRow;
fromCol = toCol;
int[][] moves = getRestrictedBasicJumps(board, player, fromRow, fromCol);
boolean badExtraMove = true;
while (badExtraMove) {
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
System.out.println("Continue jump:");
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badExtraMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badExtraMove)
System.out.println("\nThis is an illegal jump destination :(");
}
// Apply extra jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
}
}
return board;
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a strategy. *
* --------------------------------------------------------- */
public static int[][] getStrategyFullMove(int[][] board, int player, int strategy) {
if (strategy == RANDOM)
board = randomPlayer(board, player);
else if (strategy == DEFENSIVE)
board = defensivePlayer(board, player);
else if (strategy == SIDES)
board = sidesPlayer(board, player);
showBoard(board);
return board;
}
/* --------------------------------------------------------- *
* Get a strategy choice before the game. *
* --------------------------------------------------------- */
public static int getStrategyChoice() {
int strategy = -1;
getStrategyScanner = new Scanner(System.in);
System.out.println("Choose the strategy of your opponent:" +
"\n\t(" + RANDOM + ") - Random player" +
"\n\t(" + DEFENSIVE + ") - Defensive player" +
"\n\t(" + SIDES + ") - To-the-Sides player player");
while (strategy != RANDOM & strategy != DEFENSIVE
& strategy != SIDES) {
strategy=getStrategyScanner.nextInt();
}
return strategy;
}
/* --------------------------------------- *
* Print the possible moves *
* --------------------------------------- */
public static void printMoves(int[][] possibleMoves) {
for (int i = 0; i < 4; i = i+1) {
for (int j = 0; j < possibleMoves.length; j = j+1)
System.out.print(" " + possibleMoves[j][i]);
System.out.println();
}
}
/* --------------------------------------- *
* Mark/unmark the possible moves *
* --------------------------------------- */
public static void markPossibleMoves(int[][] board, int[][] moves, int fromRow, int fromColumn, int value) {
for (int i = 0; i < moves.length; i = i+1)
if (moves[i][0] == fromRow & moves[i][1] == fromColumn)
board[moves[i][2]][moves[i][3]] = value;
showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Shows the board in a graphic window *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void showBoard(int[][] board) {
grid.showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Print the board *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void printMatrix(int[][] matrix){
for (int i = matrix.length-1; i >= 0; i = i-1){
for (int j = 0; j < matrix.length; j = j+1){
System.out.format("%4d", matrix[i][j]);
}
System.out.println();
}
}
}
hi. just started coding for , installed ide intellij but i cant run the code.
thanks so much!
As you can see the green arrow of the run command is disabled. in addition when i try to run from the run menu of the toolbar it just says edit configuration.

Just place cursor to the "main" method line and press right button and select run.

Right click in main method code and tap Run.

Related

Java - create 2 different matrices with same variables

I'm currently working on a version of Conway's Game of Life with Netbeans IDE and I wanted to store cells in a matrix. For the operation of going to the Next generation of cells, I would return a new matrix of cells which is calculated from the inputting matrix.
The Code is the following:
public static Cell[][] nextGen(Cell[][] CellList)
{
Cell[][] Copy = CellList.clone();
for (int i = 0; i<Copy.length; i++)
{
for(int n = 0; n<Copy[i].length; n++)
{
if (Copy[i][n].isAlive())
{
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4 )
{
CellList[i][n].kill();
}
}else
{
if (Cell.count(Copy, i, n) == 3)
{
CellList[i][n].born();
}
}
}
}
return CellList;
}
The Class is called "Cell"
it has a private boolean property "alive" which can be set to false with the public method kill() or true with the public method born(). Everything except the method for counting alive cells surrounding a specific cell and the method for calculating the new generation is nonstatic.
The Problem why it isn't working is that if I make any changes to the input matrix "CellList", the same thing happens in the copy of this matrix.
How can I let the copy have the same Values but only make changes in the input matrix?
Thanks for the helping!
What you are doing is shallow copy, what you need is deep copy. Try this
public class Cell {
boolean alive = false;
protected Cell clone() {
return new Cell(this);
}
public Cell() {
}
public Cell(Cell cell) {
this.alive = cell.alive;
}
boolean isAlive() {
return alive;
}
void kill() {
alive = false;
}
void born() {
alive = true;
}
static int count(Cell[][] cell, int j, int k) {
return 1;
}
public static void main(String[] args) {
Cell[][] CellList = new Cell[2][3];
CellList[0][1] = new Cell();
nextGen(CellList);
}
public static Cell[][] nextGen(Cell[][] CellList) {
Cell[][] Copy = deepArrayCopy(CellList);
for (int i = 0; i < Copy.length; i++) {
for (int n = 0; n < Copy[i].length; n++) {
if (Copy[i][n].isAlive()) {
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4) {
CellList[i][n].kill();
}
} else {
if (Cell.count(Copy, i, n) == 3) {
CellList[i][n].born();
}
}
}
}
return CellList;
}
public static Cell[][] deepArrayCopy(Cell[][] celllist) {
Cell[][] copy = new Cell[celllist.length][celllist[0].length];
for (int i = 0; i < celllist.length; i++) {
for (int k = 0; k < celllist[i].length; k++) {
if (celllist[i][k] != null)
copy[i][k] = celllist[i][k].clone();
}
}
return copy;
}
}

2-D Maze Solver: Final Maze Won't Print

I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but when I run it and enter the starting position, the final maze doesn't print out.
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
//solveStack(maze);
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for
printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++)
{ //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing
values of maze
}
System.out.println(); // new line
}
}
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void restore(String[][] savedMaze) {
for (int i=0; i< ROW; i++)
for (int j=0; j<COLUMN; j++)
maze[i][j] = savedMaze[i][j];
}
public MazeGenerator clone(MazeGenerator m) {
MazeGenerator maze = new MazeGenerator();
maze = m;
return maze;
}
//**************************************************
//this solution uses a stack to keep track of possible
//states/positions to explore; it marks the maze to remember the
//positions that it's already explored.
public void solveStack() throws IOException {
//save the maze
//MazeGenerator savedMaze = new MazeGenerator();
//savedMaze.clone(m);
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "+");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty()) {
System.out.println("You got it!");
}
else System.out.println("You're stuck in the maze!");
//savedMaze.print();
print();
restore(savedMaze);
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
Without the benefit of a maze.txt, I created one based on your description. Here's what I found...
Short answer:
Your program hits an infinite loop searching for the exit, so it never reaches the code to print it out.
Long answer:
I see 3 problems on 2 lines of code:
1) A simple typo:
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
getHeight() and getWidth() should be swapped:
if (row >= 0 && col >= 0 && row < getHeight() && col < getWidth() ) {
2) In one spot, you're using 1-based indices, when Java uses 0-based indices:
In this line here:
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
Array indices in java start at 0. Your row and col variables also start at 0. But you're adding one to them thereby converting them into 1-based indices. So, you'd want:
return (maze[row][col] != "1" && maze[row][col] != "+");
3) You're using != like !equals(), but in Java, == is not the same as .equals()
In the above line of code, you're comparing two Strings with the != operator. But that doesn't work like the String.equals() method, so your Clear() method always returns true.
This is the crux of your stated problem. The search routine, finding every cell clear, works its way into a corner, and then searches the same two adjacent cells forever.
So, what you really want is:
return (!maze[row][col].equals("1") && !maze[row][col].equals("+"));

2-D Maze Solver using Stack: ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but whenever i try to run it, i get an ArrayIndexOutOfBoundsException. I think the main problem is that there are no defined walls around the border. Maybe surround the maze with a border of 1's?
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++) { //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing values of maze
}
System.out.println(); // new line
}
}
public int size() {
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col] != "1" && maze[row][col] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col<size() && row>= 0 && col<size()) {
return true;
}
else if (row < 0 && col<size() && row >= 0 && col<size()) {
return false;
}
else return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void solveStack() throws IOException {
//save the maze
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "S");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty())
System.out.println("You got it!");
else System.out.println("You're stuck in the maze!");
print();
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
The error is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MazeGenerator.Clear(MazeGenerator.java:137)
at MazeGenerator.Clear(MazeGenerator.java:141)
at MazeGenerator.solveStack(MazeGenerator.java:217)
at MazeGenerator.main(MazeGenerator.java:40)
i think you're doing a mistake in inMaze(int row, int col) method. I'll try to correct it for you
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
therefore you have to change the size() method into getWidth() and getHeight()
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}

Java battleship using arraylist: comparing user input to array list

I am trying to finish up an assignment for class I have been working on. I am supposed to build a battleship game using a location class, arraylist, and 2D array against a computer. The user gets 8 guesses on a 5x5 board. I am attacthing the directions below so it is more clear.
I am currently stuck trying to check if the users guess (in row, col form) matches the location object of a ship stored in the arraylist, however, no matter what your input, it always evaluates it as else, and marks it as a miss (aka places an X on the board). What am I doing wrong?
directions page 1
directions page 2
Here is my code so far:
driver class:
import java.util.Random; import java.util.Scanner; import java.util.ArrayList;
public class battleshipDriver {
public static void main(String[] args) {
//fields
char [][] board = new char[5][5]; // game board array
ArrayList<Location> Location1 = new ArrayList<>(); // array list to hold location objects
initialBoard(board); // prints initial board state
Random computer = new Random(); //create num gen for computer placements
int row, col;
Scanner user = new Scanner(System.in);
//stuff that is doing things
//puts comp's placements in Location
for(int i = 0; i <= 4; i ++) {
row = computer.nextInt(5);
col = computer.nextInt(5);
Location battleship = new Location(row, col);
Location1.add(battleship);
}
System.out.println(Location1);
int turnsLeft = 8;
int numShips = 4;
do {
System.out.println("You have " + turnsLeft + " turns left." + "\n"
+ "There are " + numShips + " ships left.");
System.out.println("Please make a guess (row, column)");
row = user.nextInt();
col = user.nextInt();
Location userGuess = new Location(row, col);
if(row>4 || col>4 ) {
System.out.println("Your move is invalid.");
}
else if (board[row][col] == 'X' || board[row][col] == '*') {
System.out.println("You have already guessed that location");
}
for(Location loc: Location1) {
if(Location1.contains(userGuess)) {
Location1.remove(userGuess);
board[row][col] = '*';
updateBoard(board);
System.out.println("You hit a ship");
break;
}
else {
board[row][col] = 'X';
updateBoard(board);
break;
}
}
}while(turnsLeft != 0);
}
//printBoard method
public static void initialBoard(char[][] board) {
//for loops iterate through each
for(int row = 0; row< board.length; row++) {
for(int col = 0; col < board[row].length; col++) {
board [row][col] = 'O'; //assigns O to signify open water
//(this may need to change. Most likely
//will always make the board O's only
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
public static void updateBoard(char[][] board) {
for(int row = 0; row< board.length; row++) {
for(int col = 0; col < board[row].length; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
}
location class:
public class Location {
private int row;
private int col;
//getters and setters
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int row) {
this.row = row;
}
public void setCol(int col) {
this.col = col;
}
//constructors
public Location(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return row + ", " + col ;
}
}
I currently have the array list printing its contents so that I can just input known ship locations to see if i get it working properly.
The Location class must override equals and hashCode for ArrayList#contains(...) to work. That's your problem and its solution.
Make row and col final fields and use them to check for equality and to calculate the hashCode (you must only use invariants to do this).
Something like:
package pkg1;
public class Location {
private final int row;
private final int col;
// getters and setters
public int getRow() {
return row;
}
public int getCol() {
return col;
}
// make the field immutable!
// public void setRow(int row) {
// this.row = row;
// }
// make the field immutable!
// public void setCol(int col) {
// this.col = col;
// }
// constructors
public Location(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return row + ", " + col;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + col;
result = prime * result + row;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Location other = (Location) obj;
if (col != other.col)
return false;
if (row != other.row)
return false;
return true;
}
}
In the contains(...) method entry in the ArrayList API:
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
So as you can see, the method uses the .equals(...) method to check for containment.

NullPointerException when using 2D array

My goal is to traverse a maze using a stack, but I am unable to get very far.
I have a 2D array of Room objects and I always start at position 1,1. I believe I have everything set up correctly. However, I keep getting a NullPointerException whenever I try to access the data stored in my array.
Any assistance that will point me in the right direction would be appreciated.
Here is my room class:
import java.awt.Point;
public class Room {
private Room up;
private Room down;
private Room left;
private Room right;
private char value;
private boolean blocked;
private boolean visited = false;
private Point p;
public void setCord(int row, int column) {
p = new Point(row, column);
}
public void setUp(Room [][] r, int row, int column) {
up = r[row][column];
}
public void setDown(Room[][] r, int row, int column) {
down = r[row][column];
}
public void setRight(Room[][] r, int row, int column) {
right = r[row][column];
}
public void setLeft(Room[][] r, int row, int column) {
left = r[row][column];
}
public void setValue(char c) {
value = c;
}
public void setVisited(boolean b) {
visited = b;
}
public void setBlocked(boolean b) {
blocked = b;
}
public Point getCord() {
return p;
}
public Room getUp() {
return up;
}
public Room getDown() {
return down;
}
public Room getRight() {
return right;
}
public Room getLeft() {
return left;
}
public char getValue() {
return value;
}
public boolean getVisited() {
return visited;
}
public boolean getBlocked() {
return blocked;
}
}
Here is my maze class:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.JOptionPane;
public class Maze {
String inFile, // Name of file to be used as input
outFile, // Name of file to output completed maze to
line; // Current line being read by scanner
char [][] mazeContent;
Room [][] rooms;// Holds the values that create maze
Room [] theStack;
Room current = new Room();
ArrayList<Room> al;
int rows, columns;
int tos = 0;
char [][] mazeC;
public static void main(String []args) throws Exception {
Maze m = new Maze();
}
public Maze() throws FileNotFoundException {
// Prompts user for the name of the file they wish to use as the input file.
inFile = JOptionPane.showInputDialog(null, "Please enter the name of the file you wish to read, including " +
"the file path:");
//if(inFile.equals("")) inFile = "C:\Java\JavaFiles\maze1.txt;
// Prompts user to enter the name they wish to save the file under.
outFile = JOptionPane.showInputDialog(null, "Please enter the filename you wish to save the data to:");
// Creates a scanner object to read in the input file.
Scanner readFile = new Scanner(new FileReader(inFile));
PrintWriter output = new PrintWriter(outFile);
rows = readFile.nextInt();
columns = readFile.nextInt();
readFile.nextLine();
theStack = new Room[1000];
mazeContent = new char [rows][columns];
rooms = new Room [rows][columns];
theStack = new Room[1000];
for(int i = 0; i < rows; i++) {
line = readFile.nextLine();
for(int j = 0; j< line.length(); j++) {
mazeContent[i][j] = line.charAt(j);
}
}
createRooms();
findPath();
}
private void findPath() {
Room start = rooms[1][1];
push(start);
while(!isEmpty()) {
current = pop();
//System.out.println("The value is " + current.getValue());
if(current.getValue() == '$') {
System.out.println("Success");
}
else if(current.getBlocked() != true && current.getVisited() != true) {
current.setVisited(true);
push(current.getRight());
push(current.getLeft());
push(current.getUp());
push(current.getDown());
}
}
}
public void createRooms() {
for(int i = 1; i < rows - 1; i++) {
for(int j = 1; j < columns -1; j++) {
Room r = new Room();
r.setCord(i,j);
r.setValue(mazeContent[i][j]);
r.setUp(rooms, i-1, j);
r.setDown(rooms, i+1, j);
r.setRight(rooms, i, j+1);
r.setLeft(rooms, i, j-1);
if(mazeContent[i][j] == '*')
r.setBlocked(true);
else
r.setBlocked(false);
rooms[i][j] = r;
}
}
}
private Room pop() {
return theStack[--tos];
}
private boolean isEmpty() {
// TODO Auto-generated method stub
return tos == 0;
}
private void push(Room item) {
if (isFull()) {
System.out.println("The stack is full!");
}
else
theStack[tos++] = item;
}
private boolean isFull() {
return tos == theStack.length-1;
}
}
The most likely root cause of your NullPointerException is that you have not (fully) initialized something. Perhaps a field of one of your objects. Perhaps an element of on of your arrays. When you then try to use this uninitialized field or array element, you are actually trying to perform an operation on a null reference ... and that causes the exception.
If the exception is being thrown by
if(current.getValue() == '$')
then that means that current is null. That means that you "popped" a null from your stack. On first sight, the implementations of your stack operations look OK, so my guess is that somewhere you have pushed a null.
My suggestion is to add a test in the push method that throws an exception if you attempt to push null. (Or try and track this down using a debugger.) Then continue working backwards to figure out where the null came from.

Categories

Resources