I'm currently writing a program that creates the game tic tac toe. The app as it is right now has two people play at against each other, taking turns entering the row and column number. The main problem I'm having with this program is that I cannot get it to display the results of whether one person wins or loses or both players tie. If anyone has any suggestions as to how I can solve this that would be great. Thanks again for your time.
import java.util.Scanner;
public class ticTacToeApp {
// 1. GAME CONSTANTS
static final int WIN = 1;
static final int LOSE = 0;
static final int TIE = 2;
static final int GAME_IN_PROGRESS = 3;
static final String PLAYER = "X";
static final String OPPONENT = "O";
static final String EMPTY = " ";
// 2. INPUT STREAM
static Scanner in;
public static void main(String[] args) {
// 3. BUILD THE TIC TAC TOE 3X3 BOARD OF STRINGS
String[][] board = { { EMPTY, EMPTY, EMPTY }, { EMPTY, EMPTY, EMPTY },{EMPTY, EMPTY, EMPTY } };
// 4. INSTANTIATE THE SCANNER FOR INPUT
in = new Scanner(System.in);
// 5. GAME ENGINE
drawBoard(board);
int moveResult = GAME_IN_PROGRESS; // STATUS OF THE GAME AND AFTER A
// MOVE
while (moveResult == GAME_IN_PROGRESS) {
// PLAYER MOVES AND BOARD IS CHECKED FOR A RESULT
getMove(board, PLAYER, in);
drawBoard(board);
if (moveResult != GAME_IN_PROGRESS)
break;
// OPPONENT MOVES AND THE BOARD IS CHECKED FOR A RESULT
getMove(board, OPPONENT, in);
drawBoard(board);
moveResult = boardResults(board);
}
// 6. ONCE THE GAME HAS ENDED, DISPLAY IT IS AS A WIN, LOSE, OR TIE.
if (moveResult == WIN)
System.out.println("You win.");
else if (moveResult == LOSE)
System.out.println("You lost.");
else
System.out.println("You tied.");
}
public static int boardResults(String[][] board) {
// TASK 1: BUILD AN ARRAY CONTAINING ALL THE ROW, COLUMN, AND
// DIAGONAL STRING ARRANGEMENTS ON THE CURRENT
// TIC TAC TOE BOARD.
String[] waysToWin = new String[8];
int i = 0; // INDEX TO wayToWin
for (int r = 0; r < 3; r++) {
String str = " ", stc = " ";
for (int c = 0; c < 3; c++) {
str += board[r][c];
stc += board[c][r];
}
waysToWin[i++] = str;
waysToWin[i++] = stc;
// ADD 2 DIAGONALS
waysToWin[i++] = board[0][0] + board[1][1] + board[2][2];
waysToWin[i++] = board[0][2] + board[1][1] + board[2][0];
// TASK 2. CHECK IF ANY OF THESE ARRANGEMENTS CONTAIN A WINNING
// "XXX" OR
// "OOO"
// NOTE: AN "XXX" IS WIN AND AN "OOO" IS LOSE.
for (int p = 0; p < 8; p++) {
if (waysToWin[p].equals("XXX"))
return WIN;
if (waysToWin[p].equals("OOO"))
return LOSE;
// TASK 3. CHECK IF THE BOARD IS FULL (TIE) OR IF THE GAME IS
// STILL IN
// PROGRESS
if (board[0][0] == EMPTY || board[0][1] == EMPTY || board[0][2] == EMPTY || board[1][0] == EMPTY
|| board[1][1] == EMPTY || board[1][2] == EMPTY || board[2][0] == EMPTY || board[2][1] == EMPTY
|| board[2][2] == EMPTY)
return GAME_IN_PROGRESS;
}
}
return i;
}
public static void drawBoard(String[][] board) {
for (int row = 0; row < board.length; row++) {
System.out.println("___________");
for (int col = 0; col < board[row].length; col++) {
System.out.print("|" + board[row][col] + " ");
}
System.out.println("| ");
}
System.out.println("___________");
}
public static void getMove(String[][] board, String whoseMove, Scanner in) {
int[] xy = new int[2];
for (;;) {
System.out.print("You are " + whoseMove + ". ");
System.out.println("Enter the row and column of your move: ");
xy[0] = in.nextInt();
xy[1] = in.nextInt();
if (board[xy[0]][xy[1]].equals(EMPTY))
break;
System.out.println("You must choose an empty space.");
}
board[xy[0]][xy[1]] = whoseMove;
}
}
I would use a single dimensional array for the board and create an array of winning combinations that indexes into the board. Then loop through the winning combinations and count X's and O's. If you have 3, then declare a winner. Here is a snippet demonstrating:
public class ticTacToeApp {
static final String X = "X";
static final String O = "O";
static final String N = " ";
public static void main(String[] args) {
String[] board = { X,X,O,
N,O,N,
O,N,N };
// combinations to win:
int[][] wins = { {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,6,8}, {0,4,8}, {2,4,6} };
// count x's and o's to win
int x=0, o=0;
// find the winner by indexing the board array from the combinations to win array
// In each combination to win, if all 3 are X's or O's, declare a winner
for(int i=0; i<8; i++) {
x=0; o=0;
for(int j=0;j<3;j++) {
if (board[wins[i][j]] == X) x++;
if (board[wins[i][j]] == O) o++;
}
if (o==3 || x==3)
System.out.println(((x==3) ? "X" : "O") + " wins");
}
}
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Thats my tictactoe game and i have this problem i cant find out...When i compile my programm
Welcome To Tic Tac Toe Professor Falken!
***Use Numbers 1-9 To Select A Square***
_1_|_2_|_3_|
_4_|_5_|_6_|
_7_|_8_|_9_|
You Go First!
___|___|___|
___|___|___|
___|___|___|
Player X, enter move (1 - 9):
10
INVALID MOVE: Enter number 1 - 9 only:
5
___|___|___|
___|_X_|___|
___|___|___|
Player O, enter move (1 - 9):
___|___|___|
___|_X_|_O_|
___|___|___|
Player X, enter move (1 - 9):
4
___|___|___|
_X_|_X_|_O_|
___|___|___|
Player O, enter move (1 - 9):
And stops there, i dont know why can anyone help me?
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private Scanner in;
private boardPiece[][] board = {{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()}};
private char turn = 'X';
private boolean win = false;
private int count = 0;
private Random random = new Random();
private int randomNumber = random.nextInt(9);
public static void main(String [] args)
{
int replay;
TicTacToe game = new TicTacToe();
game.in = new Scanner(System.in);
System.out.println("Welcome To Tic Tac Toe Professor Falken!");
System.out.println("***Use Numbers 1-9 To Select A Square***");
System.out.println("_1_|_2_|_3_|");
System.out.println("_4_|_5_|_6_|");
System.out.println("_7_|_8_|_9_|");
System.out.println(" n You Go First!");
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
while(replay != 2){
game.init();
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
}
game.in.close();
System.out.println("How about a nice game of chess :p");
}
public void play()
{
printBoard();
while(!win)
move();
}
public void printBoard()
{
for(int x=0; x<3; x++){
for(int y=0; y<3; y++){
System.out.print(board[x][y].piece);
}
System.out.println();
}
}
public void move()
{
int move = 0;
String valid = "";
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if(turn == 'O') {
move = randomNumber; }
else {
move = in.nextInt();
}
valid = checkMove(move);
while(valid != "ok")
{
if(turn == 'X') {
System.out.println("INVALID MOVE: "+ valid);
move = in.nextInt();
}
else {
move = randomNumber;
}
valid = checkMove(move);
}
count++;
board[(move-1)/3][(move-1)%3].piece = "_"+turn+"_|";
board[(move-1)/3][(move-1)%3].player = turn;
board[(move-1)/3][(move-1)%3].used = true;
printBoard();
if(count >= 5)
checkWin(move);
if(turn == 'X')
turn = 'O';
else
turn = 'X';
}
public String checkMove(int move)
{
if(move < 1 || move > 9)
return "Enter number 1 - 9 only: ";
else
if(board[(move-1)/3][(move-1)%3].used)
return "That move has been used. Enter another move (1 - 9): ";
else
return "ok";
}
public void checkWin(int move)
{
for(int x = 0; x<3; x++){ //Horizontal
if((board[x][0].used && board[x][1].used && board[x][2].used) &&
(board[x][0].player == board[x][1].player && board[x][0].player == board[x][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
for(int y = 0; y<3; y++)
{
if((board[0][y].used && board[1][y].used && board[2][y].used) &&
(board[0][y].player == board[1][y].player && board[0][y].player == board[2][y].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
if((board[0][0].used && board[1][1].used && board[2][2].used) &&
(board[0][0].player == board[1][1].player && board[0][0].player == board[2][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if((board[2][0].used && board[1][1].used && board[0][2].used) &&
(board[2][0].player == board[1][1].player && board[2][0].player == board[0][2].player))
{
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if(count==9){
System.out.println("Draw! Nobody Wins (´???`)");
win = true;
return;
}
}
public void init()
{
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
board[x][y] = new boardPiece();
}
}
turn = 'X';
win = false;
count = 0;
}
class boardPiece{
public String piece;
public char player;
public boolean used;
boardPiece(){
piece = "___|";
used = false;
}
}
}
I made a some changes in move and checkMove
public void move() {
int move = 0;
Boolean valid = false;
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if (turn == 'O') {
move = randomNumber;
} else {
move = in.nextInt();
}
valid = checkMove(move);
while (!valid) {
if (turn == 'X') {
move = in.nextInt();
} else {
move = random.nextInt(9);
}
valid = checkMove(move);
}
count++;
board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_|";
board[(move - 1) / 3][(move - 1) % 3].player = turn;
board[(move - 1) / 3][(move - 1) % 3].used = true;
printBoard();
if (count >= 5) {
checkWin(move);
}
if (turn == 'X') {
turn = 'O';
}else {
turn = 'X';
}
}
public Boolean checkMove(int move) {
if (move < 1 || move > 9) {
System.out.println("INVALID MOVE: Enter number 1 - 9 only: ");
return false;
}else if (board[(move - 1) / 3][(move - 1) % 3].used) {
System.out.println("INVALID MOVE: That move has been used. Enter another move (1 - 9): ");
return false;
}else {
return true;
}
}
I'm learning Java for my own and i have this problem:
I created a poker program, and every time, both the AI and I draw nothing but the Ace of Spades (5 each) every round. How can I fix this?
import java.io.IOException;
import java.util.Scanner;
public class poker {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int score1 = 0,score2 = 0;
for (int i=0; i<10; i++) {
int[][] previous_cards = new int[0][2];
int[][] hand1 = generate_hand(previous_cards);
int[][] sorted1 = sort_hand(hand1);
System.out.println("Round "+(i+1)+": ");
System.out.print(" Your hand: ");
print_hand(sorted1);
int identify_hand1 = identify_hand(sorted1);
System.out.print(" ");
print_identify_hand(identify_hand1);
System.out.println();
int[][] hand2 = generate_hand(hand1);
int[][] sorted2 = sort_hand(hand2);
System.out.print(" Computer hand: ");
print_hand(sorted2);
int identify_hand2 = identify_hand(sorted2);
System.out.print(" ");
print_identify_hand(identify_hand2);
System.out.println();
int compared = compare_hands(sorted1,sorted2);
if (compared==-1)
System.out.println(" You win this round!");
else if (compared==1)
System.out.println(" The computer wins this round!");
else System.out.println("Draw!");
score1 += (compared<0)?1:0;
score2 += (compared>0)?1:0;
System.out.println(" Score: You:"+score1+" - Computer:"+score2);
input.nextLine();
}
if (score1<score2)
System.out.println("The computer won with: "+score2+"-"+score1+".");
else if (score1==score2)
System.out.println("Draw: "+score1+"-"+score2+".");
else System.out.println("You won with: "+score1+"-"+score2+".");
}
public static int[][] generate_hand(int[][] previous_cards) {
int[][] hand = new int[5][2];
return hand;
}
public static int[] generate_card() {
int[] card = new int[2];
card[0] = (int) (Math.random()*13 + 2);
card[1] = (int) (Math.random()*4 + 1);
return card;
}
public static int compare_2_cards(int[] card1, int[] card2) {
return 0;
}
public static void print_hand(int[][] hand) {
System.out.print(card_to_String(hand[0])+", ");
System.out.print(card_to_String(hand[1])+", ");
System.out.print(card_to_String(hand[2])+", ");
System.out.print(card_to_String(hand[3])+", ");
System.out.print(card_to_String(hand[4]));
}
public static String card_to_String(int[] c) {
String card = "";
if (2<=c[0] && c[0]<=10)
card += c[0];
else if (c[0]==11) card += "Jack";
else if (c[0]==12) card += "Queen";
else if (c[0]==13) card += "king";
else card += "Ace";
card += " of ";
if (c[1]==1) card += "hearts";
else if (c[1]==2) card += "diamonds";
else if (c[1]==2) card += "clubs";
else card += "spades";
return card;
}
public static int[][] sort_hand(int[][] hand) {
int[][] sorted = new int[5][2];
return sorted;
}
public static void print_identify_hand(int identify_hand) {
if (identify_hand==1)
System.out.print("(straight flush)");
else if (identify_hand==2)
System.out.print("(four of a kind)");
else if (identify_hand==3)
System.out.print("(full house)");
else if (identify_hand==3)
System.out.print("(four of a kind)");
else if (identify_hand==4)
System.out.print("(flush)");
else if (identify_hand==5)
System.out.print("(straight)");
else if (identify_hand==6)
System.out.print("(three of a kind)");
else if (identify_hand==7)
System.out.print("(two pairs)");
else if (identify_hand==8)
System.out.print("(one pair)");
else
System.out.print("(nothing - high hand comparison)");
}
public static int compare_hands(int[][] hand1,int[][] hand2) {
// IMPLEMENT: compare 2 cards
return 1;
}
public static int identify_hand(int[][] hand) {
if (hand[0][1]==hand[1][1] && hand[1][1]==hand[2][1] && hand[2][1]==hand[3][1] && hand[3][1]==hand[4][1] && // compare that they have the same suit
hand[0][0]+1==hand[1][0] && hand[1][0]+1==hand[2][0] && hand[2][0]+1==hand[3][0] && hand[3][0]+1==hand[4][0]) // compare card numbers
return 1;
if (hand[0][0]==hand[1][0] && hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0]) // compare card numbers
return 2;
if (hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0] && hand[3][0]==hand[4][0]) // compare card numbers
return 2;
return 9;
}
}
Your int[][] hand objects are empty.
The generate_hand method returns an empty array, sort_hand returns another empty array, the other methods don't alter the array at all.
You end up passing empty (for int arrays, that means that each index contains 0) arrays to card_to_String, which then displays the result for c[0] == 0 and c[1] == 0, you got it...this is Ace of spades.
I am writing a Tic Tac Toe game and need to ask if the user wants to play again, (y/n). I have the game working, I'm just not sure how to loop it if the user hits y, and/or terminate it if the user hits n. I've tried several different things but can't seem to figure any of them out, so this is just my working code posted. Any help would be greatly appreciated!
import java.util.Scanner;
public class Assignment7 {
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char[][] board = new char[3][3];
public static char turn = 'X';
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
/*create for-loop
* 9 empty spots, 3x3
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static void Play() {
//find if game over
boolean playing = true;
PrintBoard();
while (playing) {
System.out.println("Please enter a row, then a column: ");
//make row next thing player types
row = scan.nextInt() - 1;
//same with column
col = scan.nextInt() - 1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game over! Player " + turn + " wins!");
}
PrintBoard();
//switch players after entries
if (turn == 'X') {
turn = 'O';
} else {
turn = 'X';
}
}
}
public static void PrintBoard() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
//get dividers on left
if (j == 0) {
System.out.print("| ");
}
// get dividers in all
System.out.print(board[i][j] + " | ");
}
}
//enter space after board
System.out.println();
}
public static boolean GameOver(int rMove, int cMove) {
// Check perpendicular victory
if (board[0][cMove] == board[1][cMove]
&& board[0][cMove] == board[2][cMove]) {
return true;
}
if (board[rMove][0] == board[rMove][1]
&& board[rMove][0] == board[rMove][2]) {
return true;
}
// Check diagonal victory
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]
&& board[1][1] != '_') {
return true;
}
return false;
}
}
Simply use a do-while loop and wrap it around your "game" code...
When the Play method returns, prompt the user if they want to play another game, loop until they answer with anything other then "Y", for example
String input = null;
do {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
if (scan.hasNextLine()) {
scan.nextLine();
}
System.out.print("Do you want to play a game [Y/N]? ");
input = scan.nextLine();
} while ("y".equalsIgnoreCase(input));
I am having trouble with my hangman programm in java class I don't seem to get the lost lives counter to work properly and also displaying the already guessed letters that are right don't display in the sequence when you make the next correct guess.
import java.util.Scanner; //imports scanner so I could use user input
import java.util.Random; // imports random picker for words, to pick a random word
public class javaxx {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
StringBuffer buffer = new StringBuffer();
String wordToGuess;
int wordLength;
int wordToGuessLength;
int position;
int livesLost = 0;
int totalLives = 7;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//declare variable
//String wordToGuess[] = new String[29];
//insert array for words and their values
String[] myStringArray = new String[]{"programming","exhaustive","violin","selection","repetition","serendipity","watermelon","football","mobilephone","handbag","teddybear","cardigan","waterfall","cupcake","pineapple","strawberry","collection","chicken","tablecloth","candlestick","notebook","radiator","champagne","wineyard","parent","circus","snowbell","clocktower","mermaid","cardigan"};
//Display the rules of the game
System.out.println("You are playing the game Hang Man. You have to guess the letters in the word. You will see how many letters are in the word and you have 7 changes to be wrong. ");
//choose a random word from the array
wordToGuess = myStringArray[(int) (Math.random() * myStringArray.length)];
//determine the length of the word
wordLength = wordToGuess.length();
//show the player how many letters are in the word
System.out.println("The word you are quessing has " + wordLength + " letters in it");
lettersRemaining = wordLength;
for (position = 0; position < wordLength; position++) {
sb.append("_ ");
}
System.out.println(sb.toString());
//loop starts
while (lettersRemaining > 0 && livesLost < 7) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (wordToGuess.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < wordLength; position++) {
if (wordToGuess.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("_ ");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(wordToGuess);
}
}
}
change this line
System.out.print(totalLives -= livesLost);
to
System.out.print(totalLives - livesLost);
this was the problem with liveslost counter.
Use nested for loops statements to draw hallow boxes of "*"s. The boxes have the same number of rows and columns and this number should be input from the user (valid range: 5 to 21). I'm having trouble coming up with a way to make the box hollow. this is what i have for the code and it comes as a complete square, but i need it to be hollow or just the border.
System.out.println("How many rows/columns(5-21)?");
rows=input.nextInt();
while(rows<5||rows>21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=rows;c++){
System.out.print("*");
}
System.out.println();
}
the output should look like this:
How many rows/columns (5-21)? 25
Out of range. Reenter: 7
*******
* *
* *
* *
* *
* *
*******
You need to print only some of the *s, so add a test before the print("*"). One option would be to explicitly test the four conditions (top, bottom, left, right) and OR them together logically:
if( (m==1) || //top
(m==rows) || //bottom
(c==1) || //left
(c==rows) //right
) {
System.out.print("*");
} else {
System.out.print(" ");
}
Each m== test or c== test identifies one piece of the square. Since the four tests
are ORed together, the if() is true (and a * is printed) if any one of the four tests is true. If none of them are true, the else runs and prints a space.
I also recommend renaming m to rowIndex and c to colIndex or something. When you come back to the code a week or two later, more descriptive names will make it easier to pick up where you left off. (Ask me how I know!)
import java.util.Scanner;
public class icibos {
public static void main(String[] args) {
Scanner gir = new Scanner(System.in);
System.out.print("Karenin kenarını girin: ");
int kenar = gir.nextInt();
for (int i = 1; i <= kenar; i++) {
for (int j = 1; j <= kenar; j++) {
if (i == 1 || i == kenar || j == 1 || j == kenar)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
for (int i=1;i<=lgh;i++){
for (int a=1;a<=lgh;a++){
if(i>1 && i<lgh && a>1 && a<lgh)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println("");
}
Try this , its bit hard code.
Working Example here
String myStars="*******";
String oneStar="*";
int count=0;
System.out.println(myStars);
count++;
while(count<=7)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(myStars);
You can try this
Example is Here
String pattern;
int noOfTimes;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the pattern to print : ");
pattern = scanner.nextLine();
System.out.print("Enter number of times it should get printed : ");
noOfTimes = scanner.nextInt();
for(int i=1; i<=noOfTimes; i++) {
System.out.println();
if(i==1 || i==noOfTimes) {
for(int j=1; j<=noOfTimes; j++){
System.out.print(pattern+" ");
}
}
else {
for(int k=1; k<=noOfTimes;k++) {
if(k==1 || k == noOfTimes) {
System.out.print(pattern + " ");
}
else {
System.out.print(" ");
}
}
}
}
import java.util.Scanner;
public class holsqr{
public static void main(String args[]){
Scanner ma=new Scanner(System.in);
System.out.print("Enter the number:");
int max=ma.nextInt();
for(int i=1;i<=max;i++){
for(int j=1;j<=max;j++){
if((i==1)||(i==max)){
System.out.print("#");
}else{
if(j==1||j==max){
System.out.print("#");
}
else{
System.out.print(" ");
}
}
}
System.out.println();
}
}
}
It pretty simple, using two while loop:
public static void main(String[] args) {
int size = 0;
int r = 0;
String star = "*";
String space = " ";
System.out.print("Input size of side of square: ");
Scanner input = new Scanner(System.in);
size = input.nextInt();
while (r < size) {
int c = 0;
while (c < size) {
System.out.print(r > 0 && r < size - 1 && c > 0 && c < size - 1 ? space : star);
++c;
}
System.out.println();
++r;
}
}