I am having a little trouble with one shape I am currently trying to make here is my code currently:
import java.util.Scanner;
public class Problem2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = 0;
do
{
System.out.print("Enter an odd integer greater than or equal to 5: ");
n = input.nextInt();
}while(n < 5 || n % 2 == 0);
boxWithMinorDiagonal(n);
rightTriangle(n);
printNLetter(n);
fancySquare(n);
}
public static void fancySquare(int n)
{
System.out.println();
int tempRow = 2;
int tempCol = 2;
int tempColDec = n - 2;
int tempRowInc = 2;
for(int row = 1; row <= n; row++)
{
for(int col = 1; col <= n; col++)
{
if(row == 1 || row == n || col == 1 || col == n)
{
if(row == 1 && col == 1 || row == 1 && col == n || row == n && col == 1 || row == n && col == n)
{
System.out.print("#");
}
else
{
System.out.print("*");
}
}
else if(tempRow == row && tempCol == col)
{
System.out.print("+");
tempCol++;
tempRow++;
}
else
{
System.out.print(" ");
}
if(row == tempRowInc && col == tempColDec)
{
System.out.print("+");
tempColDec--;
tempRowInc++;
}
}
System.out.println();
}
}
}
Everything works correctly except my last method "fancySquare" is not printing out how I would like it to. It is currently printing out this shape if the user input is 9:
#*******#
*+ + *
* + + *
* + + *
* ++ *
* + + *
* + + *
*+ +*
#*******#
It should look like this instead
#*******#
*+ +*
* + + *
* + + *
* # *
* + + *
* + + *
*+ +*
#*******#
Try to use named booleans for your checks to make it more understandable.
More common is to use zero based index, but i stick to your version to make it more similar and easier to match for you.
public static void fancySquare(int n) {
System.out.println();
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
final boolean firstRow = row == 1;
final boolean lastRow = row == n;
final boolean firstCol = col == 1;
final boolean lastCol = col == n;
// calc the center
final boolean center = row == (n + 1) / 2 && col == (n + 1) / 2;
// calc the marker
final boolean marker = row == col || n - row + 1 == col;
// we need the # marker at the corners (1,1) || (1,n) || (n,1) || (n,n)
if ((firstRow || lastRow) && (firstCol || lastCol)) {
System.out.print("#");
// we need the * in the first & last column/row which is no corner
} else if (firstRow || lastRow || firstCol || lastCol) {
System.out.print("*");
// we need a # also in the center
} else if (center) {
System.out.print("#");
// we need the plus on the diagonals
} else if (marker) {
System.out.print("+");
// instead we need a space
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Related
I'm new to Java and have an assignment that requires me to create a rectangle of numbers where the numbers start from the 'user input' number and reduce to 1 in the middle (See example).
I've created a very simplified code that can do it, but I would have to create an 'else if' for each number up to the 'user input' number.
Obviously, there is a way to repeat the code using some variable, but I can't seem to figure out how to do it. Can I get some help? Here is the code I am at right now:
import java.util.Scanner;
public class Assign {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Select rectangle size:");
int user = scan.nextInt();
for (int row = 1; row <= ((user*2)-1); row++) {
for (int col = 1; col <= ((user*2)-1); col ++) {
if ((row == 1) || (col == 1) || (row == (user*2)-1) || (col == (user*2)-1)) {
System.out.printf("%2d",user);
}else if ((col == (2)) || col == (user*2)-(2) || row == 2 || row == (user*2)-(2)) {
System.out.printf("%2d",user - (1));
}else if ((col == (3)) || col == (user*2)-(3) || row == 3 || row == (user*2)-(3)) {
System.out.printf("%2d",user - (2));
}else if ((col == (4)) || col == (user*2)-(4) || row == 4 || row == (user*2)-(4)) {
System.out.printf("%2d",user - (3));
}else if ((col == (5)) || col == (user*2)-(5) || row == 5 || row == (user*2)-(5)) {
System.out.printf("%2d",user - (4));
}
}
System.out.println();
}
input.close();
}
}
I have a solution for this problem. I hope It can help you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please select your max number:");
int userChoice = input.nextInt();
int end = userChoice * 2 - 1;
int decrement = 0;
int increment = 0;
for (int i = 0; i < end; i++) {
for (int j = 0; j < end; j++) {
if(end - i - 1 < j) {
increment++;
}
System.out.print(userChoice - decrement + increment);
if(decrement < i) {
decrement++;
}
}
decrement = 0;
increment = 0;
System.out.println();
}
input.close();
}
public void odd(int[][] magic) {
int N = magic.length;
int row = N - 1;
int col = N / 2;
magic[row][col] = 1;
for (int i = 2; i <= N * N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
} else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
}
I am not able to understand the 'if' statement.
I tried to explain it (see the code i used comments)
public static void main(String[] args) {
int[][] magic = new int[7][5]; //<<Create a new Bidimentional Array
odd(magic);
}
public static void odd(int[][] magic) {
int N = magic.length; //it will take the length in position 0 from array well the 7 [7][5] so if i use [2][10] it will 2 the length DON'T TRY USE [0][n] or u'll get an error
int row = N - 1; // 7 - 1 = 6 (or your value used [VALUE_TAKEN][n])
int col = N / 2; // 7 / 2 = 3 (or your value used [VALUE_TAKEN][n])
magic[row][col] = 1; //Here you get an error if you used [0][n], BUT if you used [7][5] well it will say magic[6][3] = 1
for (int i = 2; i <= N * N; i++) { //for i=2 ; i < 14; i ++
if (magic[(row + 1) % N][(col + 1) % N] == 0) { // (col + 1) % N] = 0,(col + 1) % N] = 4, so if magic[0,4] == 0 enter
row = (row + 1) % N; //SO IF IT'S TRUE YOU ENTER
col = (col + 1) % N;
} else {
row = (row - 1 + N) % N; //it was not true
}
magic[row][col] = i; //no matter what you will be here
}
}
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am making a tic tac toe game and one of the requirements is to have the game randomly decide who goes first. I assume I should be using Math.random() but I don't know how to implement it. If anyone can, please help adjust my code thanks :)
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
Game ticTacToe = new Game();
String no = "no";
System.out.println("~~~Tic Tac Toe~~~");
System.out.println("Would you like to play?");
String playerAnswer = console.nextLine();
while(!playerAnswer.equals(no))
{
ticTacToe.play();
System.out.println("Thanks for playing");
System.out.println("Would you like to play again? Press any key for yes, type no if you don't ");
playerAnswer=console.nextLine();
}
}
}
class Game
{
private final int empty = 0;
private final int player = 1;
private final int com = 2;
private final int size = 3;
private int[][] board;
public void printScreen()
{
int col;
int row;
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print(" " + (col+1));
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
for (row = 0; row < size; row ++)
{
System.out.print((row+1) + "|");
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
System.out.print(" ");
}
else if (board[row][col] == player)
{
System.out.print("X");
}
else if (board[row][col] == com)
{
System.out.print("O");
}
System.out.print("|");
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
}
}
public void clear()
{
int col;
int row;
board = new int[size][size];
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
board[row][col] = empty;
}
}
}
public void computerMove()
{
int col;
int row;
int count;
int select;
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
select = (int) (Math.random() * count);
count = 0;
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
if (count == select)
{
board[row][col] = com;
System.out.println("The computer selects row" + (row+1) + " column " + (col+1) + ".");
}
count ++;
}
}
}
}
public void playerMove()
{
Scanner console = new Scanner (System.in);
boolean a;
int col;
int row;
a = true;
while (a)
{
System.out.println("What is your move? Select a row number from 1 to " + size + " and a column number from 1 to " + size + ".");
row = console.nextInt();
col = console.nextInt();
if ((row < 1) || (row > size) || (col < 1) || (col > size))
{
System.out.println("Invalid choice, row " + row + " or column " + col + " must be from 1 to " + size + ".");
}
else
{
row --;
col --;
if (board[row][col] != empty)
{
System.out.println("That spot is already filled");
printScreen();
}
else
{
board[row][col] =player;
a = false;
}
}
}
}
public boolean checkWinner()
{
int col;
int row;
int count;
int win;
win = empty;
for (row = 0; row < size; row ++)
{
count = 0;
if (board[row][0] != empty)
for (col = 0; col < size; col ++)
if (board[row][0] == board[row][col])
count ++;
if (count == size)
win = board[row][0];
}
for (col = 0; col < size; col ++)
{
count = 0;
if (board[0][col] != empty)
for (row = 0; row < size; row ++)
if (board[0][col] == board[row][col])
count ++;
if (count == size)
win = board[0][col];
}
count = 0;
if (board[0][0] != empty)
for (row = 0; row < size; row ++)
if (board[0][0] == board[row][row])
count ++;
if (count == size)
win = board[0][0];
count = 0;
if (board[0][size-1] != empty)
for (row = 0; row < size; row ++)
if (board[0][size-1] == board[row][size-row-1])
count ++;
if (count == size)
win = board[0][size-1];
if (win != empty)
{
if (win == player)
System.out.println("Congratz you won");
else if(win == 3)
System.out.println("you lost");
return true;
}
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
if (count == 0)
{
System.out.println("Its a tie!");
return true;
}
return false;
}
public void play()
{
boolean e;
clear();
e=false;
while (!e)
{
printScreen();
playerMove();
printScreen();
e = checkWinner();
if (!e)
{
computerMove();
e = checkWinner();
if (e)
printScreen();
}
}
}
}
There may be many ways to do this including using a Random generator class, but as tic-tac only has two players, this can simply be done as getting a boolean
boolean player1Starts = (System.currentTimeMillis() % 2) == 0;
To implement this you would have to change your play method.
public void play()
{
boolean playerTurn = Math.random() <= .5
//this function returns a value between 0 an 1 exclusive
clear();
printScreen();
while (!checkWinner())
{
if (playerTurn) {
playerMove;
} else {
computerMove();
}
playerTurn = !playerTurn;
printScreen();
}
}
What this does is first determine if the player starts.
Then it clears and prints the empty board.
Then It loops through checking if there is a winner
If there isn't a winner we go into the loop and then if its the players turn they move else the computer moves
Then we update the playerTurn to be the opposite of what it was.
Then print the screen to see the move.
If there is a winner we exit the loop and finish the play method
I have to write the code that sets an 8x8 matrix, a chessboard, and then asks the user what row and what column they want to place the queen on. I then have to put a * on each square to which the queen can move. Putting a * on the row and column the queen could move to wasn't difficult but I'm having trouble correctly labeling the diagonals to on which the queen can move. This is the code I have written so far to try and locate the diagonal:
char[][] chessboard = new char[8][8];
System.out.print("What row do you want to place the queen on? ");
int row = console.nextInt();
System.out.print("What column do you want to place the queen on? ");
int column = console.nextInt();
char queen = 'Q';
chessboard[row - 1][column - 1] = queen;
// column and rows
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
if ((i == 2 || j == 6) && chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
if ((row - 1) != 0) {
// left diagonal
for (int i = 0; i < row; i++) {
for (int j = (column - 1 - (row - 1)); ((column - 1) - (row - 1)) <= j && j < column; j++) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
for (int i = (row - 1) + (8 - (column)); i >= row - 1; i--) {
for (int j = 7; j >= (column - 1); j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
// right diagonal
for (int i = 7; i >= row - 1; i--) {
for (int j = (column - 1 - (row - 1)); 0 <= j && j < column; j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
}
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
}
When I put in experimental values, for example row 3 and column 7, I get a really messy output. For the numbers above, I get:
[][][][] * * * []
[][][][] * * * []
* * * * * * Q *
* * * * * [] * *
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
Could someone tell me where I'm going wrong?
* This is a homework question so code only in the answers, please. Thanks!
If it were me, I'd simply loop through each square of the chessboard and test the validity of each square as being one that the queen can move to, of the three possible rules, namely
square.x == queen.x ||
square.y == queen.y ||
|square.x - queen.x| == |square.y - queen.y|
If your square matches any of the above rules, then it's a valid square to move to, otherwise it's not. Omitting the square that the queen currently resides on, of course
square.x != queen.x && square.y != queen.y
Pseudocode:
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
// You could encapsulate these lines in a isValidSquareForQueenMove(x, y) method.
boolean isSquareValid = false;
isSquareValid = isSquareValid || x == queen.x;
isSquareValid = isSquareValid || y == queen.y;
isSquareValid = isSquareValid || Math.abs(queen.x - x) == Math.abs(queen.y - y);
isSquareValid = isSquareValid && x != queen.x && y != queen.y;
// Do stuff here.
}
}
So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}