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));
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;
}
}
For some reason when i ask if the user wants to play again if they say yes it will just say who won and if they say no it works fine and exits the program.
I am just looking to see what the problem is. I am not trying to be pushy and see if anyone can fix the code. I have been trying to fix it for hours any suggestions help.
import java.util.Scanner;/*
Program8C Tic Tac Toe made by Daniel Underwood on 1/31/18.
This program plays tic tac toe with no graphics but does detect who has
won
*/
import java.io.PrintStream;
import java.util.Scanner;
public class Program8C {
public static Scanner input = new Scanner(System.in);
// method generates the matrix
public static void printMatrix(char[][] matrix) {
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
System.out.println();
}
//method checks to see if the user input valid
public static boolean isUserInputValid(int userInt) {
if (userInt >= 0 && userInt < 3)
return true;
else {
System.out.println("Must be between 0 and 2.");
return false;
}
}
public static boolean isFull(char[][] matrix){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == ' ') {
return false;
}
}
}
System.out.println("The game is over, The Cat won");
return true;
}
//method detects when the game is finished
private static boolean isGameOver(char whoseTurn, char[][] matrix) {
boolean won = false;
boolean cat = false;
for (int i = 0; i < 3; i++) {
if (matrix[i][0] == whoseTurn
&& matrix[i][1] ==whoseTurn
&& matrix[i][2] == whoseTurn){
won = true;
}
for (int j = 0; j < 3; j++) {
if (matrix[0][j] == whoseTurn
&& matrix[1][j] == whoseTurn
&& matrix[2][j] == whoseTurn) {
won = true;
}
}
if (matrix[0][0] == whoseTurn
&& matrix[1][1] == whoseTurn
&& matrix[2][2] == whoseTurn) {
won = true;
}
if (matrix[0][2] == whoseTurn
&& matrix[1][1] == whoseTurn
&& matrix[2][0] == whoseTurn){
won = true;
}
}
if (won) {
System.out.printf("%c WON!!!", whoseTurn);
return true;
}
if (cat){
System.out.println("Cat has won");
}
return false;
}
private static boolean takeTurn(char whoseTurn, char[][] matrix) {
// takeTurn accepts a char which is X or O indicating whose takeTurn it is.
// we return a boolean that indicates whether the game is over or not.
int answer;
int userRow = 0;
int userCol = 0;
boolean userInputCorrect = false;
boolean locationError = false;
do {
// get whoseTurn's next move
System.out.printf("It's %c's takeTurn.", whoseTurn);
System.out.println(" ");
do {
System.out.print("Please enter row(must be between 0 and 2): ");
userRow = input.nextInt();
userInputCorrect = isUserInputValid(userRow);
} while (!userInputCorrect);
do {
System.out.print("Please enter column(must be between 0 and 2): ");
userCol = input.nextInt();
userInputCorrect = isUserInputValid(userCol);
} while (!userInputCorrect);
//if statement
if (matrix[userRow][userCol] == ' ') {
matrix[userRow][userCol] = whoseTurn;
locationError = false;
} else {
System.out.printf("Location is already taken please select another location");
locationError = true;
}
}
while (locationError);
printMatrix(matrix);
if(isFull(matrix) || isGameOver(whoseTurn, matrix)){
System.out.println(" Would you like to play again(1 for yes or 2 for No):");
answer = input.nextInt();
if (answer == 1){
new Program8C();
}
else {
System.out.println("Thank you for playing. Come back soon.");
}
}
return isGameOver(whoseTurn, matrix);
}
// main method
public static void main(String[] args) {
char[][] matrix = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
boolean done = false;
char whoseTurn = 'X';
printMatrix(matrix);
do {
//changes whose turn it is
done = takeTurn(whoseTurn, matrix);
if (whoseTurn == 'X')
whoseTurn = 'O';
else
whoseTurn = 'X';
} while (!done);
}
}
When the game is over, you should take input from the user asking to play again. You can take a variable and record user input in this variable. If user says yes, store true else false and do this while variable is true.
Have a look at the following code.
Scanner in = new Scanner(System.in);
boolean playAgain = true;
while(playAgain){
matrix = clearBoard(matrix);
do {
//changes whose turn it is
done = takeTurn(whoseTurn, matrix);
if (whoseTurn == 'X')
whoseTurn = 'O';
else
whoseTurn = 'X';
} while (!done);
String userInput = in.next();
if(userInput.equals("Yes"))
playAgain = true;
else
playAgain = false;
}
call this method to clear the board.
public char[][] clearBoard(char[][] board){
return {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
}
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");
}
}
}
I have this program needed for class and the way they ask me to complete it is confusing me as i am unable to output the proper answer. what is needed is a series of inputs that contain a series of 'x''s 'X''s and 'r''s which in turn outputs a sound. if the input contains a character that is not an 'x' 'X' or an 'r' it must output something along the lines of "please enter a valid input." For the most part i had everything down but i am unable to figure out a way to properly display the invalid input string.
import java.util.Scanner;
public class String2Beat { //main class
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("To play a drum song please enter a series of x's and r's.");
System.out.println("Use an Uppercase X for the base drum, ");
System.out.println("Use a Lowercase x for the snare drum, ");
System.out.println("Or use a Uppercase R for a rest:");
String drums = scan.nextLine();
for (int j = 0; j < 3; j++){
for (int i = 0; i < drums.length(); i++){
if (drums.charAt(i) != 'x' && drums.charAt(i) != 'X' && drums.charAt(i) != 'r'){
System.out.println("not a valid string input");
}
else {
if (drums.charAt(i) == 'X'){
System.out.println("Now playing a Bass Drum. " + drums.charAt(i));
playBass();
}
else if(drums.charAt(i) == 'x'){
System.out.println("Now playing a Snare Drum. " + drums.charAt(i));
playSnare();
}
else if(drums.charAt(i) == 'r'){
System.out.println("Now playing a Rest. " + drums.charAt(i));
playRest();
}
}
}
}
scan.close();
}
What you need to do is figure out if the String contains an invalid input before you play the sounds. Your program should probably look something like this:
import java.util.Scanner;
public class String2Beat { //main class
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("To play a drum song please enter a series of x's and r's.");
System.out.println("Use an Uppercase X for the base drum, ");
System.out.println("Use a Lowercase x for the snare drum, ");
System.out.println("Or use a Uppercase R for a rest:");
String drums = scan.nextLine();
boolean test = false;
for (int i = 0; i < drums.length(); i++)
{
if (drums.charAt(i) != 'X' || drums.charAt(i) != 'x' || drums.charAt(i) != 'R')
test = true;
}
if (!test)
{
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < drums.length(); i++)
{
if (drums.charAt(i) == 'X')
{
System.out.println("Now playing a Bass Drum. " + drums.charAt(i));
playBass();
}
else if(drums.charAt(i) == 'x')
{
System.out.println("Now playing a Snare Drum. " + drums.charAt(i));
playSnare();
}
else
{
System.out.println("Now playing a Rest. " + drums.charAt(i));
playRest();
}
}
}
}
}
else
{
System.out.println("not a valid string input");
}
scan.close();
}
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;
}
}