Java TicTacToe ArrayOutOfBounds - java

import java.util.*;
public class TicTacToe {
public static char X = 'X';
public static char O = 'O';
public static char S = ' ';
public static char[][] board = new char[3][3];
public static boolean isFull = false, win = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int c,r;
for(r=0;r<board.length;r++){
for(c=0;c<board[r].length;c++)
board[r][c] = ' ';
}
System.out.println("Player 1: X");
System.out.println("Player 2: O");
printBoard(board);
for(int i = 0; i <9 && win==false;i++){
if(i%2==0){
do {
System.out.print("Player 1: Enter your next move:(r,c) ");
r = in.nextInt();
c = in.nextInt();
if(r>board.length || c>board.length || r<0 || c<0)
System.out.println("Error, try again ");
if(board[r][c]==X || board[r][c]==O){
isFull=true;
System.out.println("This square is already taken, Player 1, try again");
}
if(board[r][c]==S){
isFull=false;
board[r][c] = X;
checkWin(board);
printBoard(board);
}
}while(isFull);
}
else{
do{
System.out.print("Enter your next move:(r,c) ");
r = in.nextInt();
c = in.nextInt();
if(r>board.length || c>board.length || r<0 || c<0)
System.out.println("Error, try again ");
if(board[r][c]==X || board[r][c]==O){
isFull=true;
System.out.println("This square is already taken, Player 2, try again");
}
if(board[r][c]==S){
isFull=false;
board[r][c] = O;
checkWin(board);
printBoard(board);
}
}while(isFull);
}
if(win)
System.out.print("We have a winner");
}
}
public static boolean checkWin(char[][] b){
int r = 0,c = 0,countX = 0,countO = 0;
for(char i = board[r][c];r<3 && c<3;r++)
System.out.println(r);
if(board[r][c]==X)
countX++;
if(board[r][c]==O)
countO++;
if(countX==3 || countO==3)
return win = true;
if(countX<3 && countO<3 && r<3){
countX = 0;
countO = 0;
r = 0;
c++;
}
return win = false;
}
public static void printBoard(char[][] b){
int r = 0,c = 0;
System.out.println();
for(r=0;r<b.length;r++){
for(c=0;c<b[r].length-1;c++)
System.out.print(" " + b[r][c] + " |");
System.out.println(" "+b[r][c]);
if(r<b.length-1){
for(c=0;c < b[r].length-1;c++)
System.out.print("---+");
System.out.println("---");
}
}
}
}
When I try to check to see if there are three in a row, it throws an ArrayOutOfBoundsException on these lines.
if(board[r][c]==X)
countX++;
if(board[r][c]==O)
countO++;
I don't know why it would throw an Exception there, considering that i am just adding to three there.

The problem is in this for loop:
for(char i = board[r][c] ; r<3 && c<3 ; r++)
When you get to r = 3, r<3 && c<3 is still false and you try to access br[r][c], which is why you get an out of bounds exception.
I suggest that you use nested loops instead of having if statement to reset. But if you really want to go that route, this is a possible construct:
for(char i = board[r][c] ; c<3 ; r++) {
...
if(r == 2) {
r=0;
c++;
}
}

int r = 0, c = 0, countX = 0, countO = 0;
for (char i = board[r][c]; r < 3 && c < 3; r++)
System.out.println(r);
if (board[r][c] == X)
countX++;
In method, checkWin. There is a for loop. In which you are iterating rows from 0 to 3.
When loops get completed rows value goes to 3.
r++ works 3 times so value is 2 and 4th time value goes 3 and condition fails.
In next statement you are checking if as
if (board[r][c] == X)
In this you are using same r value which is currently 3, so there is no element at the position of 3,0. Therefore it gives ArrayIndexOutOfBoundException.

Related

Assistance with Tic Tac Toe program

I've been working on for awhile but i can't seem to fix it and get it to wrong correctly. It tells me where the exception is but I don't see any problems.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TicTacToe.displayWinner(TicTacToe.java:243)
at TicTacToe.playerMove(TicTacToe.java:151)
at TicTacToe.playGame(TicTacToe.java:303)
at TicTacToeTester.main(TicTacToeTester.java:20)
Java Result: 1
import java.util.Scanner; //Used for player's input in game
public class TicTacToe
{
//instance variables
private char[][] board; //Tic Tac Toe Board, 2d array
private boolean xTurn; // true when X's turn, false if O's turn
private Scanner input; // Scanner for reading input from keyboard
//Constants for creation of gameboard
public final int ROWS = 3; //total rows
public final int COLS = 3; //total columns
public final int WIN = 3; //amount needed to win
public TicTacToe()
{
//creates the board
board = new char[ROWS][COLS];
for(int r = 0; r < ROWS; r++)
{
for(int c = 0; c < COLS; c++)
{
board[r][c] = ' ';
}
}
//X's turn when game starts
xTurn = true;
//creates our input object for the turn player
input = new Scanner(System.in);
}
//shows game board
public void displayBoard()
{
int colNum = 0; //number of columns
int rowNum = 0; //number of rows
//creates column labels
System.out.println(" \n");
System.out.println(" Columns ");
for (int num = 0; num < COLS; num++)
{
System.out.print(" " + colNum);
colNum++;
}
//creates vertical columns and spaces between each spot
System.out.println(" \n");
for (int row = 0; row < ROWS; row++)
{
//numbers rows
System.out.print(" " + rowNum + " ");
rowNum++;
for (int col = 0; col < COLS; ++col)
{
System.out.print(board[row][col]); // print each of the cells
if (col != COLS - 1)
{
System.out.print(" | "); // print vertical partition
}
}
System.out.println();
//creates seperation of rows
if (row != ROWS - 1)
{
System.out.println(" ------------"); // print horizontal
partition
}
}
//labels row
System.out.println("Rows \n");
}
//displays turn player
public void displayTurn()
{
if (xTurn)
{
System.out.println("X's Turn");
}
else
{
System.out.println("O's Turn");
}
}
//allows you to make move
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while(invalid)
{
System.out.println("Which row (first) then column (second)
would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to
\n"
+ "choose your position.");
row = input.nextInt();
column = input.nextInt();
//checks if spot is filled
if (row >= 0 && row <= ROWS - 1 &&
column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
//fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
}
return displayWinner(row,column);
}
public boolean displayWinner(int lastR, int lastC)
{
boolean winner = false;
int letter = board[lastR][lastC];
//checks row for win
int spotsFilled = 0;
for (int c = 0; c < COLS; c++)
{
if(board[lastR][c] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks columns for win
spotsFilled = 0;
for (int r = 0; r < ROWS; r++)
{
if(board[r][lastC] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks diagonals for win
spotsFilled = 0;
for (int i = 0; i < WIN; i++)
{
if(board[i][i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
return winner;
}
//checks if board is full
public boolean fullBoard()
{
int filledSpots = 0;
for(int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
if (board[r][c] == 'X' || board[r][c] == 'O')
{
filledSpots++;
}
}
}
return filledSpots == ROWS*COLS;
}
//plays game
public void playGame()
{
boolean finish = true;
System.out.println("Are your ready to start?");
System.out.println("1 for Yes or 0 for No? : ");
int choice = input.nextInt();
if (choice == 1)
{
while (finish)
{
displayBoard();
displayTurn();
if (playerMove())
{
displayBoard();
}
else if (fullBoard())
{
displayBoard();
System.out.println("Draw");
}
else
{
xTurn=!xTurn;
}
}
}
}
}
my tester
public class TicTacToeTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TicTacToe tictactoe = new TicTacToe();
tictactoe.playGame();
}
}
Your Player Move method has an issue take a look at this if you notice you have commented saying "// fills spot when not taken" but you misplaced the while loop bracket and included move part inside it so it threw that exception, just close the while loop bracket before moving as follows (also follow #oblivion Creations Answer these are the two issues with your code) :-
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while (invalid)
{
System.out.println("Which row (first) then column (second)" + "would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to" + "\n" + "choose your position.");
row = input.nextInt();
column = input.nextInt();
// checks if spot is filled
if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
else
{
System.out.println("Invalid position");
}
} // close while loop here
// fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
return displayWinner(row, column);
}
The reason you are getting your exception is this section of code inside your displayWinner method:
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-i] == letter)
{
spotsFilled++;
}
}
When i = 0 then COLS-i will be 3. This is outside the bounds of your array.
There are multiple ways to solve this, one would be to increase i by 1 during comparison.
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS-(i+1)] == letter)
{
spotsFilled++;
}
}
Edit: also make sure you check out Null Saints answer, as it will cause you headaches later if you don't address it now.

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

While trying to make a TicTacToe Program in Java, I keep getting a NoSuchElementException error

I have written some methods, and I keep getting a NoSuchElementException error when I try to run main, which allows me to play a Tic Tac Toe game. This occurs when I try to get a row and column value from the user, with enterMove(), as shown below:
import java.util.Scanner;
public class TicTacToeMethods {
// Create a new board for players to use
public static String[][] createBoard(){
String[][] board = new String[3][3];
for(int r = 0; r < 3; r++){
for(int c = 0; c < 3; c++){
board[r][c] = " _ ";
}
}
return board;
}
// Display the board each time a move is made
public static String displayBoard(String[][] board){
String graphicalBoard = "";
for(int r = 0; r < 3; r++){
for(int c = 0; c < 3; c++){
graphicalBoard += board[r][c];
}
graphicalBoard += "\n";
}
return graphicalBoard;
}
// Check to see if the game has been won
public static String gameWon(String[][] board){
/*
Board setup reference
A B C
D E F
G E H
A = (0,0) B = (0,1) C = (0,2)
D = (1,0) E = (1,1) F = (1,2)
G = (2,0) H = (2,1) I = (2,2)
*/
String winner = "";
boolean xWon = false;
boolean oWon = false;
// Check if X won
boolean firstRowX = (board[0][0].equals(" X ") && board[0][1].equals(" X ") && board[0][2].equals(" X "));
boolean secondRowX = (board[1][0].equals(" X ") && board[1][1].equals(" X ") && board[1][2].equals(" X "));
boolean thirdRowX = (board[2][0].equals(" X ") && board[2][1].equals(" X ") && board[2][2].equals(" X "));
boolean diagonalOneX = (board[0][0].equals(" X ") && board[1][1].equals(" X ") && board[2][2].equals(" X "));
boolean diagonalTwoX = (board[0][2].equals(" X ") && board[1][1].equals(" X ") && board[2][0].equals(" X "));
boolean[] resultsForX = {firstRowX,secondRowX,thirdRowX,diagonalOneX,diagonalTwoX};
// Check if O won
boolean firstRowO = (board[0][0].equals(" O ") && board[0][1].equals(" O ") && board[0][2].equals(" O "));
boolean secondRowO = (board[1][0].equals(" O ") && board[1][1].equals(" O ") && board[1][2].equals(" O "));
boolean thirdRowO = (board[2][0].equals(" O ") && board[2][1].equals(" O ") && board[2][2].equals(" O "));
boolean diagonalOneO = (board[0][0].equals(" O ") && board[1][1].equals(" O ") && board[2][2].equals(" O "));
boolean diagonalTwoO = (board[0][2].equals(" O ") && board[1][1].equals(" O ") && board[2][0].equals(" O "));
boolean[] resultsForO = {firstRowO,secondRowO,thirdRowO,diagonalOneO,diagonalTwoO};
for(boolean each : resultsForX){
if(each == true){
xWon = true;
break;
}
}
for(boolean each : resultsForO){
if(each == true){
oWon = true;
break;
}
}
// Return a winner, or a blank if no one has won
if(xWon){
winner = "X";
}
if(oWon){
winner = "O";
}
return winner;
}
// Validate a player's move
public static boolean validMove(int row, int column, String[][] board){
return ((board[row][column] != " X ") && (board[row][column] != " O "));
}
// Enter a move for the turn player
public static void enterMove(String turnPlayer,String[][] board){
Scanner keyboard = new Scanner(System.in);
//int row, column;
boolean valid;
System.out.print("Enter a row value for your move (1 - 3): ");
**int row = keyboard.nextInt();**
System.out.print("Enter a column value for your move (1 - 3): ");
int column = keyboard.nextInt();
valid = validMove(row - 1,column - 1,board);
while(!valid){
System.out.print("Enter a row value for your move (1 - 3): ");
row = keyboard.nextInt();
System.out.print("Enter a column value for your move (1 - 3): ");
column = keyboard.nextInt();
valid = validMove(row - 1,column - 1,board);
}
switch(turnPlayer){
case "X":
board[row - 1][column - 1] = " X ";
break;
case "O":
board[row - 1][column - 1] = " O ";
break;
default:
break;
}
keyboard.close();
}
}
Is there something wrong with me allowing the user to choose from 1 - 3, instead of 0 - 2 for the array? Or should I change something else? Thank you in advance!
Note - The problematic line has been surrounded with asterisks, in enterMove()
EDIT: Stacktrace as requested
You are closing the Scanner element,
so you are closing the underlying InputStream, System.in
So, no other Scanner can read again and a java.util.NoSuchElementException Will be thrown.

String index out of range: 4

I am a beginner here to Java. So I tried to run this code here, but it kept giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4.
I need some help. Here is my code:
import java.util.Scanner;
public class TestFour
{
public static void main(String[]args)
{
String inp= new String();
Scanner scan = new Scanner(System.in);
System.out.println("Enter Word ");
inp = scan.nextLine();
int output = 1;
int [] board = new int[40];
int points = 0;
int totalpoints = 0;
int input;
//start of for loop
for(int i = 0; i < 5; i++)
{
input = scan.nextInt();
for (int j = 0; j < inp.length(); j++)
{
//values of letters
if(inp.charAt(i) == 'a' || inp.charAt(i) == 'e')
{
points = 1;
}
else if(inp.charAt(i) == 'd' || inp.charAt(i) == 'r')
{
points = 2;
}
else if(inp.charAt(i) == 'b' || inp.charAt(i) == 'm')
{
points = 3;
}
else if(inp.charAt(i) == 'v' || inp.charAt(i) == 'y')
{
points = 4;
}
else if(inp.charAt(i) == 'j' || inp.charAt(i) == 'x')
{
points = 8;
}
else
{
points = points;
}
//checking if double letter or triple letter and executing program
if ( input % 3 == 0 && input % 6 != 0)
{
points = points * 2;
}
else
{
points = points;
}
if (input % 5 == 0 && input != 15)
{
points = points * 3;
}
else
{
points = points;
}
totalpoints = totalpoints + points;
input = input + 1;
}//end of for loop
input = input - 4;
//checking if double word or triple word and executing program
for (int k = 0; k < inp.length(); k++)
{
if (input % 7 == 0 && input != 21 && input != 25)
{
totalpoints = totalpoints * 2;
}
else
{
totalpoints = totalpoints;
}
if (input % 8 == 0 && input != 40)
{
totalpoints = totalpoints * 3;
}
else
{
totalpoints = totalpoints;
}
input = input + 1;
}
}
System.out.println(totalpoints);
}
}
The problem starts at the for loop the fifth time I enter the input. Thank you for your time. I really don't get how to fix it even though I know what is going on.
You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Simple 2d array java game

I'm trying to write a simple game in Java that creates a grid of dots using a 2d array for the user to move on. I've done that and I've gotten to the point where I'm asking the user for their movement selection, however, after that happens I want to reprint the grid with their old space empty, and with the 'o' in the space they moved to. I'm unsure how to go about reprinting the grid though, as when I first printed it I used an if statement to tell the loop where to not put dots. I'll post the code below, tips are greatly appreciated!
import java.util.Scanner;
import java.util.Random;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (gridArray[i][j] != gridArray[randomRow][randomCol] && gridArray[i][j] != gridArray[randomRow2][randomCol2])
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if ( moveSelect.equals("w"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if ( moveSelect.equals("a"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol-1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if ( moveSelect.equals("s"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow-1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if (moveSelect.equals("d"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol+1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
}
}
I think most of the problems come from general confusion about arrays. E.g. the line from the code block run when you press w:
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
sets the char value of the array at randomRow, randomCol (in this case an 'x') to the char value of the of the array space one row below it at randomRow+1, randomCol. And then the line of code after that:
gridArray[randomRow][randomCol] = ' ';
assigns a new value to that same space making the code above worthless! And in the end, randomRow and randomCol are never modified. (also you had some confusion about which way the x would move with a higher row value)
all you actually need to do in this code block is:
randomRow -= 1;
after this, you can simply reprint the whole grid with the printing code from before. Although there are other issues with this code that make it far from optimal. Also there are a similar problem in that if statement in the for loop that worked but led to problems later down the road. Simply rewriting it to fix all the things wrong, you get this:
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if ( moveSelect.equals("w"))
{
randomRow -= 1;
validInput = true;
}
else if ( moveSelect.equals("a"))
{
randomCol -= 1;
validInput = true;
}
else if ( moveSelect.equals("s"))
{
randomRow += 1;
validInput = true;
}
else if (moveSelect.equals("d"))
{
randomCol -= 1;
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
Make a method to print the grid if validInput==true
public static void printGrid(char[][]gridArray){
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
}
I modified your gridArray[randomRow][randomCol] from =' ' to ='.' because you want it to be a dot right? (If you actually want it to be a space, just leave it like it already is)
For validation, change each of the directions to things like:
if ( moveSelect.equals("w")&&randomRow!=0)
{
gridArray[randomRow][randomCol] = gridArray[randomRow-1][randomCol];
gridArray[randomRow][randomCol] = '.';
validInput = true;
}
At the end of the do,
if(validInput) printGrid(gridArray);

Categories