2D Array printing on first row - java

For some reason it prints "*" nine times on one row. Instead of a 3x3 of *.
Should also be noted that the main function simply runs the displayBoard function and would not change the output.
public class TicTacToeTwoPlayer {
static final int SIZE = 3;
/*
Here:
Declare a 2-d character array called board with SIZE rows and SIZE columns.
Be sure to use the static modifier in the declaration
*/
static char[][] board = new char [SIZE][SIZE];
static final char PLAYER1 = 'X';
static final char PLAYER2 = 'O';
static Scanner userInput = new Scanner(System.in);
public static void initializeBoard() {
/*
Here:
Initialize each position of the board array to a space character.
*/
for (int row = 0; row < board.length; row++) {
for(int col = 0; col < board.length; col++) board[row][col] = ' ';
}
}
public static void displayBoard() {
/*
Here:
Complete this method so that it displays the tic-tac-toe board
to the screen. If a board position is available, that is, if it is
a space, output an asterisk followed by a space ("* ".)
*/
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] == ' ') {
System.out.print("* ");
} else {
System.out.print(board[row][col]);
}
}
}
System.out.println("Board is: ");
}
}
Any help would be greatly appreciated!

Try printing a newline after each row:
public static void displayBoard() {
for (int row=0; row < board.length; row++) {
for (int col=0; col < board[row].length; col++) {
if (board[row][col] == ' ') {
System.out.print("* ");
}
else {
System.out.print(board[row][col]);
}
}
// print a device-independent newline here after each row
System.out.println();
}
System.out.println("Board is: ");
}

Related

How can I print a two-dimensional array of characters in Java, to create a 20x20 grid?

I am trying to print a 2d array of periods in Java, however, I can not get the formatting correctly. I am able to create a similar layout NOT using a 2d array. However, I will need to be working with a 2d array to finish the project. I have tried using Arrays.deepToString(); but did not find it useful.
My goal is to have a 20x20 grid of periods like this:
** Without the S and the X
My way without using a 2d array:
for (int i = 20; i >= 1; i--) {
for(int j = 1; j <= 20; j++) {
System.out.print(" .");
}
System.out.print("\n");
}
My try using a 2d array:
final int rows = 20;
final int columns = 20;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
System.out.println(Arrays.deepToString(board));
}
Put the two together?...
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = ".";
}
}
display2Darray(board);
}
public static void display2Darray(String[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
System.out.print(arr[row][col]);
}
System.out.println();
}
}
You have to print your 2D array outside outer loop but you print this 2D array result outside inner loop. After that you have to remove bracket and comma through java replace() method.
Here down is modified code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
// OUTER LOOP
for (int i = 0; i < rows; i++) {
// INNER LOOP
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
}
System.out.print(Arrays.deepToString(board).replace("],", "\n")
.replace(",", "")
.replace("[[", " ")
.replace("[", "")
.replace("]]", ""));
}
}

Tic-Tac-Toe display not displaying correctly

So I have created a simple tic-tac-toe console program. But for some reason my methods aren't displaying the board correctly.
The display of the code prints out like this:
Tic-Tac-Toe
------------
Player 'X', enter move (row [1-3] column [1-3]): 2
2
|
|
-----------
|
X
|
-----------
|
|
Player 'O', enter move (row [1-3] column [1-3]):
The code:
/**
* The grid represents the game board
*/
public class Grid {
int ROWS = 3; // Defines the amount of rows
int COLUMNS =3; // Defines the amount of columns
Box[][] board; // Represents the game board as a grid
int currentrow, currentcol; // Row and Column that was played last
public Grid()
{
board = new Box[ROWS][COLUMNS]; // Constructor initializes the game board
for(int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
board[row][col] = new Box(row,col);
}
}
}
public void init()
{
for (int row = 0; row < ROWS; row++) { // Re-initializes the game board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].clear();
}
}
}
public boolean isDraw()
{
for (int row = 0; row < ROWS; row++) { // Returns true if the game is a draw (no more empty boxes)
for (int col = 0; col < COLUMNS; col++) {
if (board[row][col].content == Player.EMPTY) {
return false; // An empty box found, not a draw, exits
}
}
}
return true; // No empty boxes return true is then a draw
}
public boolean hasWon(Player thePlayer) {
return (board [currentrow] [0] .content == thePlayer && board [currentrow] [1].content == thePlayer && board [currentrow] [2].content == thePlayer // 3 in a row
|| board [0] [currentcol].content == thePlayer && board [1] [currentcol].content == thePlayer && board [2] [currentcol].content == thePlayer // 3 in a column
|| currentrow == currentcol
&& board[0] [0].content == thePlayer // 3 in a diagonal
&& board[1] [1].content == thePlayer
&& board[2] [2].content == thePlayer
|| currentrow + currentcol == 2
&& board[0][2].content == thePlayer // 3 in the opposite diagonal
&& board[1][1].content == thePlayer
&& board[2][0].content == thePlayer);
}
public void paint()
{
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].paint();
if (col < COLUMNS - 1)
System.out.println("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----------");
}
}
}
}
I want the code to print out the display in the correct way. I think there must be a simple mistake I have made either in the paint() method or when I initialized the grid. Please can someone see where I have gone wrong.
You need to modify your painting methods.
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].paint();
if (col < COLUMNS - 1)
System.out.print("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----------");
}
}
First, you need to use println only when needed, the rest of the time just use print.
And the same is for Box.paint not visible here. But it seems to be using System.out.println instead of System.out.print.
Another thing, Box.paint should return a String instead of sending message in the console. The board is responsible of the painting, not the box.
public String paint(){
return content; //return a `String` " ", "X" or "O"
}
Tested with :
public static void main(String[] args) throws ParseException {
print(new String[][]{
{"X", " ", "O"},
{" ", " ", " "},
{"O", " ", "X"}
});
}
private static void print(String[][] board){
int ROWS = board.length;
int COLUMNS = board[0].length;
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
System.out.print(board[row][col]);
if (col < COLUMNS - 1)
System.out.print("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----");
}
}
}
Giving :
X| |O
-----
| |
-----
O| |X
It's hard to give you the answer with 100% certainty if you don't post all of the code. Can you add the implementation of Box and the main method?
The problem seems to be that you are doing System.out.println("|"); when you should be doing System.out.print("|");. System.out.println("|"); will also a new line causing the next thing printed to occur on the next line. You are already handling the newline for the end of the row correctly (the System.out.println(); so System.out.print("|"); should be all you need to do.
Working example with the fix: https://repl.it/repls/DimgreyOutlandishFlashdrive

Why does this Java program fail to run properly? Tic-Tac-Toe Game

I am trying to make a tic tac toe game I read about in a Java book. However the code always returns an error and I cannot figure out why. I am relatively new to coding so if the answer is obvious don't rub it in my face :). Also, no errors are displayed in the code in NetBeansIDE so I do not know what is causing the program to fail to run.
import java.util.Scanner;
public class TTT{
private String[][] tttBoard;
private String player1, player2;
public TTT(){
player1 = "X";
player2 = "O";
tttBoard = new String[3][3];
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard.length; col++){
tttBoard[row][col] = " ";
}
}
}
public void play(){
String currPlayer = player1;
int movesMade = 0;
do{
displayBoard();
makeMove(currPlayer);
movesMade += 1;
if (currPlayer == player1){
currPlayer = player2;
}
else{
currPlayer = player1;
}
}while (movesMade <= 9 && winner() == " ");
displayBoard();
System.out.println("Winner is "+winner());
}
public void displayBoard(){
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard.length; row++){
System.out.println("["+tttBoard[row][col]+"]");
}
System.out.println();
}
}
private void makeMove (String player){
Scanner input = new Scanner(System.in);
boolean validMove = false;
int row, col;
do{
System.out.print("Enter a row number (0, 1, 2): ");
row = input.nextInt();
System.out.print("Enter a column number (0, 1, 2): ");
col = input.nextInt();
if((row >= 0 && row < tttBoard.length && col >= 0 && col <
tttBoard[0].length) && tttBoard[row][col].equals(" ")){
tttBoard[row][col] = player;
validMove = true;
}
else{
System.out.println("Invalid move. Try again.");
}
}while(!validMove);
}
private String winner(){
for(int row = 0; row < tttBoard.length; row++){
if(tttBoard[row][0].equals(tttBoard[row][1]) && tttBoard[row]
[1].equals(tttBoard[row][2]) && !(tttBoard[row][0].equals(" "))){
return(tttBoard[row][0]);
}
}
for(int col = 0; col < tttBoard[0].length; col++){
if (tttBoard[0][col].equals(tttBoard[1][col]) && tttBoard[1]
[col].equals(tttBoard[2][col]) && (!tttBoard[0][col].equals(" "))){
return(tttBoard[0][col]);
}
}
if(tttBoard[0][0].equals(tttBoard[1][1]) && tttBoard[1]
[1].equals(tttBoard[2][2]) && !(tttBoard[0][0].equals(" "))){
return(tttBoard[0][0]);
}
if(tttBoard[0][2].equals(tttBoard[1][1]) && tttBoard[1]
[1].equals(tttBoard[2][0]) && !(tttBoard[0][2].equals(" "))){
return(tttBoard[0][2]);
}
return(" ");
}
}
The file that calls and runs it is as follows:
public class TicTacToe{
public static void main (String args[]){
TTT TTTGame = new TTT();
TTTGame.play();
}
}
Your displayBoard function is wrong. Notice the line:
for(int col = 0; col < tttBoard[row].length; col++)
You need to get the current row tttBoard[row] length. Another error that you made, is that you are incrementing the row instead of the col variable on the second for.
public void displayBoard(){
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard[row].length; col++){
System.out.println("["+tttBoard[row][col]+"]");
}
System.out.println();
}
}

Trying to input values into a 2d array and print it, code not running

Code not running??
import java.util.Scanner;
public class Array2dNightPractice
{
int[][] studentmarks;
studentmarks = new int[3][3];
Scanner kb = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<3;row++){
for(int col=0;col<3;col++){
studentmarks[row][col] = kb.nextInt();
}
}
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 4; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
}
you're getting IndexOutOfBoundsException because of this --> col < 4.
for(int col = 0; col < 4; col++)
change to this:
for(int col = 0; col < studentmarks[row].length; col++)
side note - make use of the length property to prevent errors such as the one you've just encountered.
full solution:
for(int row = 0; row < studentmarks.length; row++) {
for(int col = 0; col < studentmarks[row].length; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
the error comes from exceeding the bound of the array studentMarks in the second for loops at the number 4 it should be 3
A good habit to develop is to create constant variables as required with the size of each of the rows and columns, so you will not fall in such mistake.
Something like this:
import java.util.Scanner;
public class Array2dNightPractice{
public static void main(String[] agrs){
final int ROW =3, COL=3; // constant variable to determine the size of the 2d array
int[][] studentMarks = new int[ROW][COL];
Scanner in = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<ROW;row++){ //note how I don't need to memorize and rewrite the numbers every time
for(int col=0;col<COL;col++){
studentMarks[row][col] = in.nextInt();
}
}
// print the marks as matrix
for(int row =0; row <ROW; row++) {
for(int col =0; col <COL; col++) {
System.out.print(studentMarks[row][col] + " ");
}
System.out.println();
}
}
}

Draw a line in JAVA with Pattern - Beginner

I want to draw a line in java. I will use these draws with making Triangles. I can do this :
1***
11**
111*
1111
and i need to do this:
1***
*1**
**1*
***1
Ive done a lot of work today and my mind got really confused.
Can you help me ? Thanks A lot.
EDIT: also my perfect answer should be Implement Bresenham’s line drawing algorithm but i dont understand in wikipedia.
EDIT 2: my grid code :
String [][] matrix = new String [50][50];
for (int row = 0; row < 50; row++){
for (int column = 0; column < 50; column++){
matrix [row][column] = "*";
}
}
public class Test
{
public static void main(String [] args)
{
int size=50;
String[][] matrix= new String [size][size];
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
if (i != j)
matrix[i][j]="*";
else
matrix[i][j]="1";
}
}
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
}
Edit: if it's already filled with * simply make matrix[i][j]="1"; when i equals j, ie if (i==j).
public class MulArray {
public static void main(String[] args) {
/*
* 1*** 1** 1* 1
*/
String[][] grid = new String[5][5];
for (int row = 0; row < grid.length-1; row++) {
for (int column = 0; column < grid[row].length; column++) {
if (row == column) {
grid[row][column] = "1";
} else {
grid[row][column] = "*";
}
}
}
for (int row = 0; row < grid.length-1; row++)
for (int column = 0; column < grid[row].length; column++) {
if (column != 4) {
System.out.print(grid[row][column]);
}
else{
System.out.print("\n");
}
}
}
}

Categories

Resources