This question already has an answer here:
java print a triangle
(1 answer)
Closed 6 years ago.
I have to write a program to print out a triangle using "*" via methods. I have to design it to ask the user for a number to represent the number of *'s at the base of the triangle. Then print out the triangle by passing that number to your printUpTriangle() method. The only thing I have an idea about is the actual code to make the triangle which is:
public class Triangle {
public static void triangle(int levels) {
if(levels == 0)
return;
triangle(levels - 1);
for(int y = 0; y < levels; y++) {
System.out.print("*");
}
System.out.println();
}
I have to write two methods: one to return a String containing n copies of s, concatenated in a row & another one that uses your makeRow() method. It should print a right triangle in which the base of the triangle is made of n copies of s, and the vertex of the triangle has a single copy of s on the right (both methods have an int & String as variables).
public static void main (String[] args) throws java.lang.Exception
{
makeTriangle(5);
// change the above line if you need to input the number (5) from the user
}
public static void makeTriangle(Integer base_size)
{
for(int x = 1; x < base_size + 1; x++)
{
System.out.print(makeRow(x, base_size));
System.out.println();
}
}
public static String makeRow(Integer row_num, Integer base)
{
String row = "";
for(int x = base; x >= 0; x--)
{
if (x < row_num) { row += "*"; }
else row += " ";
}
return row;
}
This makes a triangle with the "vertex of the triangle has a single copy of s on the right"
So it will print out
*
**
***
****
*****
public class Triangle {
public static void main(String[] args) {
printTriangle(10);
}
public static String makeRow(int n) {
return String.format("%1$-" + n + "s", "*").replace(" ", "*");
}
public static void printTriangle(int n) {
IntStream.rangeClosed(1, n).mapToObj(Triangle::makeRow).forEach(System.out::println);
}
}
You don't need two methods, just one toString method.
public class Triangle
{
private int width;
/**
This class describes triangle objects that can be displayed
as shapes like this:
*
**
***
*/
public class Triangle
{
private int width;
/**
Constructs a triangle.
#param aWidth the number of * in the last row of the triangle.
*/
public Triangle(int aWidth)
{
width = aWidth;
}
/**
Computes a string representing the triangle.
#return a string consisting of * and newline characters
*/
public String toString()
{
String r = "";
for (int i = 1; i <= width; i++)
{
// Make triangle row
for (int j = 1; j <= i; j++)
r = r + "*";
r = r + "\n";
}
return r;
}
}
And Tester class:
import java.util.Scanner;
/**
This program prints two triangles.
*/
public class TriangleRunner
{
public static void main(String[] args)
{
System.out.println("Please enter number");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Triangle test = new Triangle(i);
System.out.println(test);
}
}
EDIT Realized that the OP needed a RIGHT triangle. I mistakenly made an equilateral triangle. New output is shown below.
If you really have to have another method to print the triangle:
import java.util.Scanner;
public class ICanHasTriangle {
static Scanner input;
static String s = "*";
public static void main(String args[]) {
input = new Scanner(System.in);
System.out.print("How wide will your base be (Enter an integer): ");
int width = input.nextInt();
boolean valid = false;
while (!valid) {
if (width <= 0) {
System.out.println("ERROR. You must enter a positive integer!");
System.out.println();
System.out.print("Try again: ");
valid = false;
width = input.nextInt();
} else {
valid = true;
printUpTriangle(s, width);
}
}
}
public static String printUpTriangle(String s, int width) {
for (int i = 0; i <= width; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(s);
}
System.out.println();
}
return s;
}
}
OUTPUT
How wide will your base be (Enter an integer): 0
ERROR. You must enter a positive integer!
Try again: 8
*
**
***
****
*****
******
*******
********
*********
Related
I am trying to create a method/ while loop which checks to see which player moves. For now I check to see which play moves in a for loop. I am trying to make my code a bit more clear and concise. Here is the main method:
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
int height = 6, width = 8, moves = height * width;
ConnectFour board = new ConnectFour(width, height);
System.out.println("Use 0-" + (width - 1) + " to choose a column.");
System.out.println(board);
for (int player = 0; moves-- > 0; player = 1 - player) { // Here is where i check to see who plays
char symbol = players[player];
board.chooseAndDrop(symbol, input);
System.out.println(board);
if (board.isWinningPlay()) {
System.out.println("Player " + symbol + " wins!");
return;
}
}
System.out.println("Game over, no winner.");
}
}
I was thinking more along the lines of:
int playerNb = 0;
while (thegamestarted)
{
if (playerNb == 0)
// Get user input
else
// Get second player input
// Process the input
// Change playerNb to 1 or 0
}
Below is the full code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ConnectFour {
private static final char[] players = new char[] { 'X', 'O' };
private final int width, height;
private final char[][] grid;
private int lastCol = -1, lastTop = -1;
public ConnectFour(int width, int height) {
this.width = width;
this.height = height;
this.grid = new char[height][];
for (int h = 0; h < height; h++) {
Arrays.fill(this.grid[h] = new char[width], '.');
}
}
public String toString() {
return IntStream.range(0, this.width)
.mapToObj(Integer::toString)
.collect(Collectors.joining()) + "\n" +
Arrays.stream(this.grid)
.map(String::new)
.collect(Collectors.joining("\n"));
}
/**
* Prompts the user for a column, repeating until a valid
* choice is made.
*/
public void chooseAndDrop(char symbol, Scanner input) {
do {
System.out.print("\nPlayer " + symbol + " turn: ");
int col = input.nextInt();
if (! (0 <= col && col < this.width)) {
System.out.println("Column must be between 0 and " +
(this.width - 1));
continue;
}
for (int h = this.height - 1; h >= 0; h--) {
if (this.grid[h][col] == '.') {
this.grid[this.lastTop=h][this.lastCol=col] = symbol;
return;
}
}
System.out.println("Column " + col + " is full.");
} while (true);
}
/**
* Detects whether the last chip played was a winning move.
*/
public boolean isWinningPlay() {
if (this.lastCol == -1) {
throw new IllegalStateException("No move has been made yet");
}
char sym = this.grid[this.lastTop][this.lastCol];
String streak = String.format("%c%c%c%c", sym, sym, sym, sym);
return contains(this.horizontal(), streak) ||
contains(this.vertical(), streak) ||
contains(this.slashDiagonal(), streak) ||
contains(this.backslashDiagonal(), streak);
}
/**
* The contents of the row containing the last played chip.
*/
private String horizontal() {
return new String(this.grid[this.lastTop]);
}
/**
* The contents of the column containing the last played chip.
*/
private String vertical() {
StringBuilder sb = new StringBuilder(this.height);
for (int h = 0; h < this.height; h++) {
sb.append(this.grid[h][this.lastCol]);
}
return sb.toString();
}
/**
* The contents of the "/" diagonal containing the last played chip
* (coordinates have a constant sum).
*/
private String slashDiagonal() {
StringBuilder sb = new StringBuilder(this.height);
for (int h = 0; h < this.height; h++) {
int w = this.lastCol + this.lastTop - h;
if (0 <= w && w < this.width) {
sb.append(this.grid[h][w]);
}
}
return sb.toString();
}
/**
* The contents of the "\" diagonal containing the last played chip
* (coordinates have a constant difference).
*/
private String backslashDiagonal() {
StringBuilder sb = new StringBuilder(this.height);
for (int h = 0; h < this.height; h++) {
int w = this.lastCol - this.lastTop + h;
if (0 <= w && w < this.width) {
sb.append(this.grid[h][w]);
}
}
return sb.toString();
}
private static boolean contains(String haystack, String needle) {
return haystack.indexOf(needle) >= 0;
}
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
int height = 6, width = 8, moves = height * width;
ConnectFour board = new ConnectFour(width, height);
System.out.println("Use 0-" + (width - 1) + " to choose a column.");
System.out.println(board);
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = players[player];
board.chooseAndDrop(symbol, input);
System.out.println(board);
if (board.isWinningPlay()) {
System.out.println("Player " + symbol + " wins!");
return;
}
}
System.out.println("Game over, no winner.");
}
}
}
Its a bit difficult to tell what you want from your code, but the absolute simplest way to keep track of what player it is, is to keep track of the turn number, and check if it is even or odd with the modulus function
This is just a brief bit of psuedocode to show you how you can tell what the turn is with simple math. You will have to adapt it to your own needs. You can see that it will only be "Player 2"'s turn on an even turn number where the turn number divided by 2 has no remainder. Just remember to increment the turn after every move.
There's no "good" answer. You're the one writing the code, you can decide whose turn it is, you just have to keep track of it.
int turn = 1;
for ( ) {
if (turn % 2 == 0) {
System.out.println("Player 2");
} else {
System.out.println("Player 1");
}
turn++;
}
Earlier post: How do I make my tictactoe program scalable
I have tried to make a Tic Tac Toe program (human vs computer) scalable (the board size can be changed). I had major problems earlier but fixed most of them.
The game's rules are basic Tic Tac Toe but one different rule is that no matter how large the board is (when >= 5) the player or computer only need five marks in a row to win.
Now the only gamebreaking problem with my program is determining who wins the game. It is only possible that the game ends a 'draw' at the moment. (Also I have not implemented the ">= 5" yet).
Specific problem explanation is that I need to determine a winner and end screen for something like "computer wins" and/or "player wins".
package tictactoe;
import java.util.Scanner;
import java.util.Random;
public class TicTacToe {
public static int size;
public static char[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);
/**
* Creates base for the game.
*
* #param args the command line parameters. Not used.
*/
public static void main(String[] args) {
System.out.println("Select board size");
System.out.print("[int]: ");
size = Integer.parseInt(scan.nextLine());
board = new char[size][size];
setupBoard();
int i = 1;
while (true) {
if (i % 2 == 1) {
displayBoard();
getMove();
} else {
computerTurn();
}
// isWon()
if (isDraw()) {
System.err.println("Draw!");
break;
}
i++;
}
}
/**
* Checks for draws.
*
* #return if this game is a draw
*/
public static boolean isDraw() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
/**
* Displays the board.
*
*
*/
public static void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%s]", board[i][j]);
}
System.out.println();
}
}
/**
* Displays the board.
*
*
*/
public static void setupBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
/*
* Checks if the move is allowed.
*
*
*/
public static void getMove() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.printf("ROW: [0-%d]: ", size - 1);
int x = Integer.parseInt(sc.nextLine());
System.out.printf("COL: [0-%d]: ", size - 1);
int y = Integer.parseInt(sc.nextLine());
if (isValidPlay(x, y)) {
board[x][y] = 'X';
break;
}
}
}
/*
* Randomizes computer's turn - where it inputs the mark 'O'.
*
*
*/
public static void computerTurn() {
Random rgen = new Random(); // Random number generator
while (true) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
if (isValidPlay(x, y)) {
board[x][y] = 'O';
break;
}
}
}
/**
* Checks if the move is possible.
*
* #param inX
* #param inY
* #return
*/
public static boolean isValidPlay(int inX, int inY) {
// Play is out of bounds and thus not valid.
if ((inX >= size) || (inY >= size)) {
return false;
}
// Checks if a play have already been made at the location,
// and the location is thus invalid.
return (board[inX][inY] == ' ');
}
}
You have already the loop to play, so, in each iteration, in the same way you check if the game isDraw(), check also if some of the players won:
while (true) {
if (i % 2 == 1) {
displayBoard();
getMove();
} else {
computerTurn();
}
// isWon()
if (isDraw()) {
System.err.println("Draw!");
break;
} else if (playerHasWon()){
System.err.println("YOU WIN!");
break;
} else if (computerHasWon()) {
System.err.println("Computer WINS!\nYOU LOOSE!!");
break;
}
i++;
}
After create the needed methods:
public static boolean playerHasWon() {
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
}
}
return hasWon ;
}
public static boolean computerHasWon() {
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
}
}
return hasWon ;
}
Next question of course is HOW DO I CREATE THIS METHODS?? dunno if you have problems with this, but doing a fast check here here and here you will find some ideas.
ADD ON:
In order to clarify, I would make a function returning an int instead booleans, to check if the game is finished using some constants:
private final int DRAW = 0;
private final int COMPUTER = 1;
private final int PLAYER = 2;
private int isGameFinished() {
if (isDraw()) return DRAW;
else if (computerHasWon()) return COMPUTER;
else if (playerHasWon()) return PLAYER;
}
Then simply check with a switch case (check here how to break the while insite the while)
loop: while (true) {
// other stufff
switch (isGameFinished()) {
case PLAYER:
System.err.println("YOU WIN!");
break loop;
case COMPUTER:
System.err.println("Computer WINS!\nYOU LOOSE!!");
break loop;
case DRW:
System.err.println("IT'S A DRAW");
break loop;
}
Every time I run my Tic Tac Toe program I can create the board and do my first turn.
After the first turn, the game just ends as: "IT'S A DRAW", which is one of the three ending possibilities. This just happens before the computer can even make his own turn.
Another problem in my program is that the scanner user input limit(er) is not working (at the end of the code). If user inputs i.e a letter instead of int, the program crashes.
package newtictactoe;
import java.util.Scanner;
import java.util.Random;
public class NewTicTacToe {
public static final int DRAW = 0;
public static final int COMPUTER = 1;
public static final int PLAYER = 2;
public static int size;
public static char[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);
/**
* Creates base for the game.
*
* #param args the command line parameters. Not used.
*/
public static void main(String[] args) {
System.out.println("Select board size");
System.out.print("[int]: ");
size = Integer.parseInt(scan.nextLine());
board = new char[size][size];
setupBoard();
int i = 1;
loop:
while (true) {
if (i % 2 == 1) {
displayBoard();
getMove();
} else {
computerTurn();
}
switch (isGameFinished()) {
case PLAYER:
System.err.println("YOU WIN!");
break loop;
case COMPUTER:
System.err.println("Computer WINS!\nYOU LOOSE!!");
break loop;
case DRAW:
System.err.println("IT'S A DRAW");
break loop;
}
i++;
}
}
private static int isGameFinished() {
if (isDraw()) {
return DRAW;
} else if (computerHasWon()) {
return COMPUTER;
} else if (playerHasWon()) {
return PLAYER;
}
return 0;
}
/**
* Checks for computer's win.
*
* #return if this game is won by computer.
*/
public static boolean playerHasWon() {
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
}
}
return hasWon;
}
/**
* Checks for player's win.
*
* #return if this game is won by computer.
*/
public static boolean computerHasWon() {
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
}
}
return hasWon;
}
/**
* Checks for draws.
*
* #return if this game is a draw
*/
public static boolean isDraw() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
/**
* Displays the board.
*
*
*/
public static void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%s]", board[i][j]);
}
System.out.println();
}
}
/**
* Displays the board.
*
*
*/
public static void setupBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
/*
* Checks if the move is allowed.
*
*
*/
public static void getMove() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.printf("ROW: [0-%d]: ", size - 1);
int x = Integer.parseInt(sc.nextLine());
System.out.printf("COL: [0-%d]: ", size - 1);
int y = Integer.parseInt(sc.nextLine());
if (isValidPlay(x, y)) {
board[x][y] = 'X';
break;
}
}
}
/*
* Randomizes computer's turn - where it inputs the mark 'O'.
*
*
*/
public static void computerTurn() {
Random rgen = new Random(); // Random number generator
while (true) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
if (isValidPlay(x, y)) {
board[x][y] = 'O';
break;
}
}
}
/**
* Checks if the move is possible.
*
* #param inX
* #param inY
* #return
*/
public static boolean isValidPlay(int inX, int inY) {
// Play is out of bounds and thus not valid.
if ((inX >= size) || (inY >= size)) {
return false;
}
// Checks if a play have already been made at the location,
// and the location is thus invalid.
return (board[inX][inY] == ' ');
}
These last two methods in the code check if the scanner input is valid but they don't work and I don't know why.
/**
* Checks if user input is valid
*
* #param scan
* #param prompt
* #return
*/
public static String getInput(Scanner scan, String prompt) {
System.out.print(prompt); // Tell user what to input
String text = "Enter one integer value i.e 5.";
while (true) { // Keeps on looping until valid input
text = scan.nextLine();
if (isInteger(text)) // Checks input is int
{
break; // Exit loop
}
System.out.print("Try again, " + prompt); // If invalid
}
return text; // Return valid user input
}
/**
* Checks if input string is int.
*
* #param str
* #return
*/
public static boolean isInteger(String str) {
try {
Integer.parseInt(str); // If this succeeds the input is int
return true;
} catch (NumberFormatException e) {
return false; // If not int
}
}
}
Your isGameFinished() method returns 0 by default (when the game is not over), but your DRAW constant is also 0. Try to change it to return (for example) -1 when the game is not over.
A nicer solution would be to have one method isGameFinished() that would return boolean to indicate if the game is over, and another method getWinner() which would return the winner (DRAW or COMPUTER or PLAYER), and will only be called if isGameFinished() returns true.
Your getMove method should catch NumberFormatException, which can be thrown by Integer.parseInt.
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.
import java.util.Scanner;
public class Ideone
{
public static void main(String[] args)
{
int reader;
Scanner kBoard = new Scanner(System.in);
do
{
System.out.println("Insert a number of rows: ");
reader = kBoard.nextInt();
printDiamond(reader);
}while(reader != 0);
}
public static void printWORD(int n)
{
if(n >= 1)
{
System.out.print("SAMPLE");
printWORD(n - 1);
}
}
public static void printTopTriangle(int rows)
{
int x = 1;
for(int j = (rows - 1); j >= 0; j--,x +=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printSpaces(int n)
{
if(n >= 1)
{
System.out.print(" ");
printSpaces(n - 1);
}
}
public static void printBottomTriangle(int rows, int startSpaces)
{
int x = 1 + (2*(rows - 1));
for(int j = startSpaces; j <= (rows) && x > 0; j++,x -=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printBottomTriangle(int rows)
{
int x = 1 + (2*(rows - 1));
for(int j = 0; j <= (rows - 1) && x > 0; j++,x -=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printDiamond(int rows)
{
printTopTriangle((int)rows/2 + 1);
printBottomTriangle((int)rows/2, 1);
}
}
My program is supposed to show a Diamond Shape made out of the word "SAMPLE." But when I run it, it displays a space ship shape. How do I fix this error so it would print a perfect Diamond with the word "SAMPLE"?
Change these methods as follows:
public static void printTopTriangle(int rows)
...
printSpaces(j*6);
public static void printBottomTriangle(int rows, int startSpaces)
...
printSpaces(j*6);
Note: 6 is the length of the constant SAMPLE
Because of the size of "SAMPLE" (6 chars), you have to indent with System.out.print(" "); (ie. 6 spaces not 1).
Runnable demo: http://ideone.com/JHTU6C
NB: I didn't fix anything else (you might want to check if an int exists before asking for it with nextInt())
If you change "SAMPLE" with "*" or any other char you get a diamond shape. You get a space ship shape because you don't put enough spaces in printSpaces method. Number of spaces should be close the number of chars that you print in printWORD method. Put 5 or 6 spaces in printSpaces method and you will get something close to a diamond.