I'm trying to build a Christmas tree with a user inputted triangular top and a rectangular base, but I'm currently stuck while building the base. The specifications are as follows: The triangle starts with a single * and increases the amount of * on each row by a total of 2 per line, such that the final row is 2(n)-1 with n being the inputted height of the triangle. The height of the rectangle (stump) underneath the tree is equal to 1 plus (1/5)n and the width of the stump is 1/3n however if the result of 1/3n is an even integer, add 1 to the total stump width. (i.e the stump width is always an odd number.)
Here's what i have so far, the triangular part of the tree is fine, but the rectangle is a mess.
public class xmasTree {
public static final int TREE_MAXIMUM = 20;
public static final int TREE_MINIMUM = 3;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//User introduction
System.out.println("This program prints a \"Christmas\" tree. You "
+ "choose how big the tree will be (within reason);
// prompt for and get user input
System.out.println("How tall should the top of the tree be?");
int treeHeight = keyboard.nextInt();
while (treeHeight < TREE_MINIMUM || TREE_MAXIMUM < treeHeight) {
System.out.println("That's not a valid size. I can only do trees "
+ "from 3 to 20.");
System.out.println("Qutting now.");
System.exit(0);
}
//Print the top triangle section of the christmas tree
for (int i = 0; i < treeHeight; i++) {
for (int j = 0; j < treeHeight - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < (2 * i + 1); k++) {
System.out.print("*");
}
System.out.println();
}
//Print the bottom rectangle section of the tree
for (int c = 0; c <= (1 + (treeHeight / 5)); c++) {
for (int d = 0; d <= (treeHeight / 3); d++) {
System.out.print("");
}
System.out.printf("*");
}
}
}
If anyone could help me figure out how to get the proper input shape for the rectangle that would be awesome, I know I can center it with a simple printf once it is built properly.
First, you need to visualize what your result should be.
Example, n = 8, so base should be 1 + n/5 = 2 tall and n / 3 = 2 adjusted to 3 wide.
*
***
*****
*******
*********
***********
*************
***************
***
***
Your code has the following problems:
print("") is a meaningless statement. It does nothing.
You don't print any leading spaces for indentation.
You don't print * for a count equal to base width.
You don't call println() so base height will definitely not work.
You got the tree part good, so you really shouldn't have problems with this. I won't give you the answer, but hopefully this visual example will help you do it yourself.
And if you make your for loop start at 0, then don't use a equal sign, as it will work 1 more time to what you expect
You almost made it, just a couple comments about your code:
In the last for you should have used < instead of <= like you did on the beggining
You had clear the rules so you just needed to write them in your code, like I did in my code try to make it more clear, find the height and the width of the stump before writing it out
In the inner for you should have printed out the * and in the outer for you just needed to print a new line
Scanner keyboard = new Scanner(System.in);
//User introduction
System.out.println("This program prints a \"Christmas\" tree. You "
+ "choose how big the tree will be (within reason)");
// prompt for and get user input
System.out.println("How tall should the top of the tree be?");
int treeHeight = keyboard.nextInt();
while (treeHeight < TREE_MINIMUM || TREE_MAXIMUM < treeHeight) {
System.out.println("That's not a valid size. I can only do trees "
+ "from 3 to 20.");
System.out.println("Qutting now.");
System.exit(0);
}
//Print the top triangle section of the christmas tree
for (int i = 0; i < treeHeight; i++) {
for (int j = 0; j < treeHeight - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < (2 * i + 1); k++) {
System.out.print("*");
}
System.out.println();
}
//Print the bottom rectangle section of the tree
int stumpHeight = (1 + (treeHeight / 5));
int stumpWidth;
if ((treeHeight / 3) % 2 == 0) {
//it is even add 1
stumpWidth = (treeHeight / 3) + 1;
} else {
//it is odd keep it like that
stumpWidth = (treeHeight / 3);
}
for (int c = 0; c < stumpHeight; c++) {
//sorry for adding the spaces but I don't like the incomplete answers
//centering
for (int d = 0; d < treeHeight - stumpWidth/2; d++) {
System.out.print(" ");
}
//adding stump
for (int d = 0; d < stumpWidth; d++) {
System.out.print("*");
}
//going to the next line
System.out.println();
}
Related
I have to create a lottery game where you randomly generate six winning numbers simulating a lottery. Ask the user to enter six numbers and see if they win the lottery!
I have done a lot of it, but now im stuck. I am really new to java so forgive me. When it prompts to ask for another number it does it but it still displays it for the self-made lottery picks that display. Also, when displaying the numbers for the computer made lottery picks they are the same numbers over again that repeat and aren't 6 numbers. The counter doesn't work as well it maybe a little thing but i can't figure it out. Thank you
package arraysIntroduction;
import java.util.Scanner;
public class sizeQuestion {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int [] user =new int [6];
int i;
//Fill user array
System.err.println("Welcome to Miwand's Lottery");
System.out.println("Please enter your 6 desiered number to enter the lottery");
System.out.println("Pick from 1 to 49");
for ( i=0;i<user.length;i++) // gets numbers until it equals 6
{
System.out.println("Number:");
user[i]= in.nextInt(); // Gets numbers from user
while (user[i] < 0 ) // if its a negative number tell user to enter again
{
System.err.println("Negative number, please enter again:");
user[i]=in.nextInt();
}
if (user[i] > 49) // if the number goes past 49 prompt again
{
System.err.println("Please enter numbers from 1 - 49");
}
}
//print out the numbers generated
for ( i=0;i < user.length; i++){
System.out.print(+user[i]+ " ");
}
System.out.println(" ");
int[] lottery = new int[6];
int guesses;
int counter=0;
int j;
int x;
{
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() *49 +1); // Random number created here.
for ( x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() *49 +1);// If random number is same, another number generated.
}
lottery[j] = randomNum;
}
}
//prints out computer generated numbers
for (i = 0; i < lottery.length; i++){
for (x = 0; x< j; x++){
System.out.print(lottery[i] + " ");
if (user[i] == lottery[x] ){
counter++;
}
}
}
}
if (counter < 2){
System.out.println("Try again!");
}
if (counter == 3){
System.out.println("3 numbers matched! You won $300!");
}
if (counter == 4){
System.out.println("4 numbers matched! You won 500!");
}
if (counter == 5){
System.out.println(" 5 numbers matched! You won $1000!");
}
else if (counter == 6){
System.out.println("JACCKKKPOOOOTTTTTTT!!!!!! YOU WIN 1 MILLION DOLLARS!");
}
}
}
I saw multiple problems in your program.
First, the printout problem can be solved by moving the print statement from inner loop to outer loop
for (i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) {
if (user[i] == lottery[x]) {
counter++;
}
}
}
Also, you are not assigning the first random number correctly and it is always using the default, which is 0
Solution:
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() * 49 + 1); // Random number created here.
for (x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 49 + 1);// If random number is same, another number generated.
}
}
lottery[j] = randomNum;
}
Plus, you didn't check if counter is equal to 2
Solution:
if (counter <= 2) {
System.out.println("Try again!");
}
And, the logic in "If random number is same, another number generated." may not be correct, since it may generate the same number again. You need a while loop to generate a new number until it is not equal to any of the generated numbers.
Another thing about coding style is that for any "for loops"
This :
int i=0;
for (i = 0; i < length; i++)
Should be replaced by this:
for (int i = 0; i < length; i++)
As I already said in the comments, you should move the print statement from the inner loop to the outer loop.
Your code should look like this:
for (i = 0; i < lottery.length; i++) { // outer loop
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) { // inner loop
if (user[i] == lottery[x]) {
counter++;
}
}
}
i have an issue with my 2d array its not outputting correctly, so the program is running fine, however when i choose case 4 to view airplane seating chart horizontally outputting to many x's and not in the correct spot. if any one can point me in the right direction that will be awesome!
public static void viewSeatingChartVertical(boolean seat[]){
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 3; ++j){
if(seat[((j + 1) + (i * 3)) - 1])
System.out.print("x ");
else
System.out.print("o ");
}
System.out.println();
}
}
public static void viewSeatingChartHorizontal(boolean seat[]){
int [][] twoDim = new int [3][10];
int a = (twoDim.length);
int b = (twoDim[0].length);
for(int i = 0; i < a; i++){
for(int j = 0; j < b; j++) {
int x = 0;
twoDim[i][j] = x;
if(seat[((j + 1) + (i * 3)) - 1])
System.out.print("x ");
else
System.out.print("o ");
}
System.out.println();
}
}
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);// if the system doesnt know the Scanner function it then looks to import it
boolean seating[] = new boolean[30];//declare the amount of seats available on the plane in an array
//display list of options - saving space make easier to read on smaller screen
System.out.println("Please choose an option:");
System.out.println("1 for “first class”");
System.out.println("2 for “economy”");
System.out.println("3 to view seating chart");
System.out.println("4 to view seating horizontally chart");
System.out.println("0 to exit");
System.out.print("? ");
while(true){ //loop while valid
int mOpt = input.nextInt(); //mOpt Menu Option - validate number entered, must be 0-4
switch (mOpt){
case 0: System.exit(0);
break; //system exit
case 1: // first class seats
{
System.out.print("Which seat would you like (1-9)\n");
int fcseat = input.nextInt();
if(fcseat > 0 && fcseat <10){
if(seating[fcseat - 1]){
System.out.print("That seat is taken.\n");
}
else{
seating[fcseat - 1] = true;
System.out.print("Seat number " + fcseat + " was assigned.\n");
}
}
}
break;
case 2: // economic seats
{
System.out.print("Which seat would you like (10-30)\n");
int econSeat = input.nextInt();
if(econSeat >= 10 && econSeat <= 30){ // HAD 31 NOT 30. SMH
if(seating[econSeat - 1]){
System.out.print("That seat is taken.\n");
}
else{
seating[econSeat - 1] = true;
System.out.print("Seat number " + econSeat + " was assigned.\n");
}
}
}
break;
case 3: //printout of available seats vertically
{
viewSeatingChartVertical(seating);
}
break;
case 4: //printout of available seats horizontally
{
viewSeatingChartHorizontal(seating);
}
break;
default: //wrong format or number please try again
System.out.print("Sorry, Option not recognized, please Try again.\n");
}
}
}
}
You are mixing up rows and columns on the plane with rows and columns on the screen.
Your horizontal output is really over complicated. It should be just as simple as the vertical output. The key is duplicate the code from your vertical output, but reverse the two for statements.
for(int j = 0; j < 3; ++j) {
for(int i = 0; i < 10; ++i) {
and it should magically work.
Well, almost work. This will flip the left and right sides of the plane. A small change to the first loop will fix that too. Left to student.
I'm currently doing a java memory game that makes the user guess duplicate letters by input the coordinate of either a 2x2, 4x4 or 6x6 square, which have 2 sets of repeating letters
ex. for 4x4 it would be
A B C D
E F G H
A B C D
E F G H
but randomized
If they guess correctly the letters would stay revealed, until all are found.
I have successfully randomized the square, and cover it with ( * ), and make them reveal based on the input coordinates
But I don't know how to make that once the 2 revealed letters are the same, the program will keep them revealed through out the game, until all duplicate letters are revealed.
The code right now (You can copy and paste whole thing below, all comments are commented out):
import java.util.Scanner;
import java.io.IOException;
public class a4{
// main method. DO NOT MODIFY
public static void main(String args[]) {
Scanner keyboard = new Scanner( System.in );
System.out.println("Welcome to Memory Game");
int board_side;
//this loop obtains the board size, or more specifically
// the length of the side of the board
do{
System.out.println("\n For 2x2 board game press 2"+
"\n For 4x4 board game press 4"+
"\n For 6x6 board game press 6");
board_side=keyboard.nextInt();
}while(board_side!=2 && board_side!=4 && board_side!=6);
char[][] board = createBoard(board_side);
// a call the the shuffle method
shuffleBoard(board);
// a call to the game playing method
playGame(board);
}
// The following method should shuffle the input 2D array caled board
public static void shuffleBoard(char[][] board)
{
// This creates a 1D array whose size is equal to the size of the board
int N = board.length*board.length;
char[] board1D = new char[N];
// Testing to see the printed square
for ( int i = 0; i < board.length; i++) {
for ( int j = 0; j < board[i].length; j++) {
System.out.print( board[i][j] + " " );
}
System.out.println();
}
System.out.println();
for (int i =0; i < board1D.length; i++) {
System.out.print(board1D[i] + " ");
}
System.out.println();
// Copy the elements of 2D array into that 1D array here
for (int m = 0; m < N; m++){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board.length; j++, m++){
board1D [m] = board[i][j];
}
}
}
// Shuffle 1D array
// Shuffle the array
for (int i = 0; i < N; i++) {
// Generate an index randomly
int index = (int)(Math.random() * N);
char temp = board1D[i];
board1D[i] = board1D[index];
board1D[index] = temp;
}
//Testing to see the 1D array
System.out.println();
for (int i =0; i < board1D.length; i++) {
System.out.print(board1D[i] + " ");
}
System.out.println();
//Copy shuffled 1D array back into 2D array, i.e., back to the board
for (int m = 0; m < N; m++){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board.length; j++, m++){
board[i][j] = board1D [m];
}
}
}
//Testing to print the shuffled square
for ( int i = 0; i < board.length; i++) {
for ( int j = 0; j < board[i].length; j++) {
System.out.print( board[i][j] + " " );
}
System.out.println();
}
System.out.println();
System.out.println();
}
// game playing method
public static void playGame(char[][] board)
{
Scanner keyboard = new Scanner( System.in );
// this createst a 2D array indicating what locations are paired, i.e., discovered
// at the begining none are, so default initializaiton to false is ok
boolean[][]discovered=new boolean[board.length][board[0].length];;
for ( int i = 0; i < board.length; i++) {
System.out.print(1 + i + " ");
for ( int j = 0; j < board[i].length; j++) {
System.out.print( "* " );
}
System.out.println();
}
System.out.print(" ");
for ( int x = 0; x < board.length; x++) {
System.out.print(1 + x + " ");
}
System.out.println();
System.out.println();
System.out.println("Enter a pair of undiscovered distinct locations on the board that you want revealed. i.e., a pair of integers in the range [1, 2]");
System.out.println();
int FirstLocationX;
int FirstLocationY;
int SecondLocationX;
int SecondLocationY;
do {
System.out.println("Enter the first location: ");
FirstLocationX=keyboard.nextInt();
FirstLocationY=keyboard.nextInt();
if (FirstLocationX > board.length && FirstLocationY > board.length){
System.out.println("The location is invalid. It is outside of the board. ");
}
} while(FirstLocationX > board.length && FirstLocationY > board.length);
System.out.println();
do {
System.out.println("Enter the second location: ");
SecondLocationX=keyboard.nextInt();
SecondLocationY=keyboard.nextInt();
if (SecondLocationX > board.length && SecondLocationY > board.length){
System.out.println("The location is invalid. It is outside of the board. ");
}
else if (SecondLocationX == FirstLocationX && SecondLocationY == FirstLocationY){
System.out.println("The location is invalid. The second location equal to the first. ");
}
} while(SecondLocationX > board.length && SecondLocationY > board.length && SecondLocationX == FirstLocationX && SecondLocationY == FirstLocationY);
//reveals the letters based on the coordinate user inputed
for ( int i = 0; i < board.length; i++) {
System.out.print(1 + i + " ");
for (int j = 0; j < board[i].length; j++) {
if (FirstLocationX == i+1 && FirstLocationY == j+1){
System.out.print( board[i][j] + " " );
}
else if (SecondLocationX == i+1 && SecondLocationY == j+1){
System.out.print( board[i][j] + " " );
}
/*This part is wrong, reveals the whole square instead of the found duplicates
else if (discovered[0][0] = true){
System.out.print( board[i][j] + " " );
}
else if (discovered[0][2] = true){
System.out.print( board[i][j] + " " );
}
*/
else {
System.out.print( "* " );
}
}
System.out.println();
}
System.out.print(" ");
for ( int x = 0; x < board.length; x++) {
System.out.print(1 + x + " ");
}
System.out.println();
System.out.println();
char[][] FirstInput = new char[FirstLocationX][FirstLocationY];
char[][] SecondInput = new char[SecondLocationX][SecondLocationY];
/*GETTING AN ERROR HERE when I try to trigger a duplicate letter found, since the array is shuffled I don't know how exactly, just testing with the first match right now (A and A), which suppose to be coordinate 0,0 and 0,2 in the non-sorted square matrix
*/
if (board[0][0] == FirstInput[FirstLocationX][FirstLocationY] && board[0][2] == SecondInput[SecondLocationX][SecondLocationY]){
discovered[0][0] = true;
discovered[0][2] = true;
}
waitForPlayer();
do {
playGame(board);
}while(discovered[0][0] == false && discovered[0][2] == false);
}
// createBoard method. DO NOT MODIFY!
/* this method, createBoard, creates the board filled with letters of alphabet,
where each letter appears exactly 2 times
e.g., for 4 x 4, the returned board would look like:
A B C D
E F G H
A B C D
E F G H */
public static char[][] createBoard(int side)
{
char[][] tmp = new char[side][side];
int letter_count=0;
for (int row = 0; row < tmp.length/2; row++){
for(int col = 0; col < tmp[row].length; col++)
{
tmp[row][col]=(char)('A'+letter_count);
tmp[row+tmp.length/2 ][col]=tmp[row][col];
letter_count++;
}
}
return tmp;
}
// waitForPlayer method. Do not modify!
public static void waitForPlayer()
{
System.out.print("Press enter to continue");
try {
System.in.read();
}
catch (IOException e){
System.out.println("Error reading from user");
}
}
}
The current part that is wrong is:
char[][] FirstInput = new char[FirstLocationX][FirstLocationY];
char[][] SecondInput = new char[SecondLocationX][SecondLocationY];
/*when I try to trigger a duplicate letter found, since the array is shuffled I don't know how exactly, just testing with the first match right now (A and A), which suppose to be coordinate 0,0 and 0,2 in the non-sorted square matrix
*/
if (board[0][0] == FirstInput[FirstLocationX][FirstLocationY] && board[0][2] == SecondInput[SecondLocationX][SecondLocationY]){
discovered[0][0] = true;
discovered[0][2] = true;
}
waitForPlayer();
do {
playGame(board);
}while(discovered[0][0] == false && discovered[0][2] == false);
}
and
else if (discovered[0][0] = true){
System.out.print( board[i][j] + " " );
}
else if (discovered[0][2] = true){
System.out.print( board[i][j] + " " );
}
I would suggest making each square as an object instead of having a mere char. That way you can control if they are revealed or not when you display then
Edit
Without objects, you can just create another array of bool that will track what is displayed. Whenever a pay is revealed, set the values inside that alternative board to true, then in your display function check if it is true before showing it
I would do the following:
Create an char[][] array in which the amount of * equals the input characters.
e.g.:
ABCD
DACB
'*****'
'****'
Get the coordinates which the user enters and compare them logically, if both characters are the same, then replace the corresponding * with the character.
e.g:
if the user input would be 0,0 for the first char and 1,1 for the second (both A)
then update the array to:
ABCD
DACB
A***
*A**
all the lines will be in one array but in the game you would print only the second two rows. The offset between the first two rows and the second two rows is the same, so it should be no problem to do that.
Hi I created a Magic Square program in java
It works fine if you input a number 3 but if i input 5 and so on
there's a problem occurring..
The pattern becomes wrong.
Please help me to find out what's wrong in my code:
Here's my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
// Number must be ODD and not less than or equals to one to continue
while ((num % 2 == 0) || (num <= 1)) {
System.out.println("Enter a valid number: ");
num = input.nextInt();
}
int[][] magic = new int[num][num];
int row = 0;
int col = num / 2;
magic[row][col] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic[(row + 5) % num][(col + 2) % num] == 0) {
row = (row + 5) % num;
col = (col + 2) % num;
} else {
row = (row + 1 + num) % num;
}
magic[row][col] = i;
}
for (int x = 0; x < num; x++) {
for (int j = 0; j < num; j++) {
System.out.print(magic[x][j] + "\t");
}
System.out.println();
}
}
It's correct when i Input 3,
here's the output:
But when i type a number like 5:
It becomes:
UPDATED!
You seem to be trying to implement the Method for constructing a magic square of odd order.
The method prescribes starting in the central column of the first row with the number 1.
You seem to have that right.
After that, the fundamental movement for filling the squares is diagonally up and right, one step at a time.
I would code this as:
int newRow = row - 1;
int newCol = col + 1;
When an "up and to the right" move would leave the square, it is wrapped around to the last row or first column, respectively.
This is clearly:
if ( newRow < 0 ) {
newRow = num - 1;
}
if ( newCol > num - 1 ) {
newCol = 0;
}
If a filled square is encountered, one moves vertically down one square instead, then continues as before.
if (magic[newRow][newCol] != 0) {
newRow = row + 1;
newCol = col;
}
I know this doesn't actually solve your problem but I hope it gets you somewhere towards your goal. See how I take the words of the algorithm and match them as accurately as possible with code.
I am trying to write a program in Java that captures an integer from the user (assume data is valid) and then outputs a diamond shape depending on the size of the integer, i.e. User enters 5, output would be:
--*--
-*-*-
*---*
-*-*-
--*--
So far I have:
if (sqr < 0) {
// Negative
System.out.print("#Sides of square must be positive");
}
if (sqr % 2 == 0) {
// Even
System.out.print("#Size (" + sqr + ") invalid must be odd");
} else {
// Odd
h = (sqr - 1) / 2; // Calculates the halfway point of the square
// System.out.println();
for (j = 0; j < sqr; j++) {
for (i = 0; i < sqr; i++) {
if (i != h) {
System.out.print(x);
} else {
System.out.print(y);
}
}
System.out.println();
}
}
Which just outputs:
--*--
--*--
--*--
--*--
--*--
I was thinking about decreasing the value of h but that would only produce the left hand side of the diamond.
void Draw(int sqr) {
int half = sqr / 2;
for (int row = 0; row < sqr; row++) {
for (int column = 0; column < sqr; column++) {
if ((column == Math.abs(row - half))
|| (column == (row + half))
|| (column == (sqr - row + half - 1))) {
System.out.print("*");
} else {
System.out.print("_");
}
}
System.out.println();
}
}
Ok, now this is the code, but as I saw S.L. Barth's comment I just realised this is a homework. So I strongly encourage you to understand what is written in this code before using it as final. Feel free to ask any questions!
Take a look at your condition:
if (i != h)
This only looks at the column number i and the midway point h.
You need a condition that looks at the column number and the row number. More precisely, you need a condition that looks at the column number, the row number, and the distance of the column number from the midway point.
Since this is a homework question, I leave determining the precise formula to you, but I'm willing to drop some more hints if you need them. Good luck!
You can use two nested for loops from -h to h, where h is half a diamond. The edge of a diamond is obtained when:
Math.abs(i) + Math.abs(j) == h
If user input n=5, then h=2, and a diamond looks like this:
n=5, h=2
--*--
-*-*-
*---*
-*-*-
--*--
Try it online!
// user input
int n = 9;
// half a diamond
int h = n / 2;
// output a diamond shape
System.out.println("n=" + n + ", h=" + h);
for (int i = -h; i <= h; i++) {
for (int j = -h; j <= h; j++) {
if (Math.abs(i) + Math.abs(j) == h) {
System.out.print("*");
} else {
System.out.print("-");
}
}
System.out.println();
}
Output:
n=9, h=4
----*----
---*-*---
--*---*--
-*-----*-
*-------*
-*-----*-
--*---*--
---*-*---
----*----