Making Tree with Nested Loops - java

So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");

I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}

Related

Printing a word in a diamond format

My assignment is to print a word in the shape of a diamond like so:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
*e*******e
**d*****d
***i***i
****p*p
*****s
P.S. The asterisks are only there to show spacing, pretend one asterisk represent one space.
So far I have this:
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
//r*********r
//*e*******e
//**d*****d
//***i***i
//****p*p
//*****s
}
}
Which prints the first half of the diamond perfectly:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
The only part where I'm getting stuck is when I have to print the latter half of the diamond. Can anyone point me in the right direction? Please do not write the code for me, just try and give me some pointers based off the logic I've shown. Thank you.
Try to have only one loop. A very easy way to handle the "technicalities" of the problem is to work with an char array for the output. First you initialize it with the proper length, fill it with blanks (there is a library function for it), fill the two characters, and only then convert it to a String.
The only open question is where to put the characters, and I don't want (and should) to spoil that.
int fullLength = 2 * word.length() - 1;
for(int i = 0; i < fullLength; i++) {
char[] line = new char[fullLength];
Arrays.fill(line, ' ');
int k = ???;
char c = s.charAt(k);
line[word.length() - 1 - k] = c;
line[word.length() - 1 + k] = c;
System.out.println(new String(line));
}
Obviously, you want to calculate the position "from the middle" (so we have something like word.length() - 1 +- k), and for the first half of the word, k is equal to i.
Your task, should you decide to accept it, is to find out how to "bend k back" for the second half of the word.
import java.util.Scanner;
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
int wordLength2 = word.length();
int wordSize = word.length();
int wordLengthReverse = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
System.out.print(" " + word.charAt(wordLength2-2));
int spaceLength =((wordLength2*2)-1) -4;
int u =spaceLength -2;
for(int i =0; i < spaceLength; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordLength2-2));
System.out.println();
int m=3;
for(int num =2; num<wordSize-1; num++)
{
wordLength2 = num;
for(int i =0; i<num; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
for(int b = 0; b<u; b++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
System.out.println();
m++;
u = u-2;
}
for(int r =0; r<word.length()-1; r++)
{
System.out.print(" ");
}
System.out.print(word.charAt(0));
}
}
I have finished. This is my final code. I understand it is not as efficient as possible, or easy to follow, but it is flexible and not hard-coded, so I am content.

Printing diamonds from *'s

I am trying to System.out.print() a diamond out of *'s. So far I have spent a good 5 hours on trying to figure out how to reverse print the bottom triangle of the diamond.
I can worry about the spacing to complete the diamond later. (I have it worked for the most part).
If someone could explain to me what I am doing wrong and how the right way works I would greatly appreciate it.
private static void diamond()
{
int numLines = 0;
System.out.println("How many lines would you like in the Diamond?");
numLines = scan.nextInt();
if (numLines / 2 == 0) //if number is even, make odd.
{
numLines++;
}
for(int i = 0; i <= numLines ; i++) // Controls #Lines
{
if(i <= numLines / 2)
{
for(int j = 0; j < i * 2 - 1; j++) // Controls #Stars small upright triangle
{
System.out.print("*");
}
}
else
{
for(int k = numLines; k > i / 2; k--) // Controls # of spaces
{
System.out.print("*");
}
/*for(int j = numLines/2 - i, l = i; l > j; j++) // Controls #Stars small upright triangle
{
String stars = "*";
System.out.print(stars);
}*/
}
System.out.println("");
}
}
`
What happens to your attempt is that you loop through the half (of the lines) of your diamond [the number of lines in second/first half] times.
You'd want to do a if-statement each loop, not an if and a for in each loop
Probably you want this
Just adjust it for user input values
public static void main(String[] args) {
System.out.print("Reverse diamond: \n");
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
System.out.print("\n\nDiamond from starts: \n");
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
}
output:

Cannot get the addition to output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Out of Bounds Error in 2D Array with Dice Program

So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int x = console.readInt();
System.out.print("Enter the amount of sides: ");
int y = console.readInt();
System.out.print("Enter the amount of die: ");
int z = console.readInt();
int[][] dice = new int[x][z];
int row = 0;
for (int i = 0; i<z; ++i){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x)) {
i = 0;
++row;
}
}
row = 0;
int[] sum = new int[x];
for (int j = 0; j<z; ++j){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x)) {
j = 0;
++row;
}
}
int[] counter = new int[2*y];
int k = 0;
while (k<sum.length){
for (int l = 0;l<((2*y)-1);++l){
if (sum[k]==l) ++counter[l];
if (l==((2*y)-1)) {
++k;
}
}
}
for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");
}
}
first loop:
for (int i = 0; i<z; i++){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x-1)) {
i = -1;
++row;
}
}
second loop:
for (int j = 0; j<z; j++){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x-1)) {
j = -1;
++row;
}
}
Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...
There are x rows but you are using z as the row loop
int[][] dice = new int[x][z]; <-- x is the row count
int row = 0;
for (int i = 0; i < z; ++i){ <--- The outer loop is iterating the rows (x),
Here's how to iterate through a 2D array
int[][] dice = new int[x][z];
for (int i = 0; i < x; i++){
for (int j = 0; j < z; j++){
// do something with dice[i][j]
}
}

How do i complete this question with 2-dimensional array in java?

Hey guys, im working through the Introduction to Programming in Java book and one of the exercises is this:
Empirical shuffle check. Run
computational experiments to check
that our shuffling code works as
advertised. Write a program
ShuffleTest that takes command-line
arguments M and N, does N shuffles of
an array of size M that is initialized
with a[i] = i before each shuffle, and
prints an M-by-M table such that row i
gives the number of times i wound up
in position j for all j. All entries
in the array should be close to N/M.
Now, this code just outputs a block of zeros...
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
for (int i = 0; i < M; ++i)
deck [i] = i;
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
for(int n = 0; n < N; n++) {
int r = i + (int)(Math.random() * (M-i));
int t = deck[r];
deck[r] = deck[i];
deck[i] = t;
for (int b = 0; b < N; b++)
{
for (int c = 0; c < M; c++)
System.out.print(" " + a[b][c]);
System.out.println();
}
}
}
}
}
}
What am i doing wrong? :(
Thanks
So a is like a history? As you are now it is always filled with zeroes just like you initialized, you never assign to it! After the "shuffling" for loop you need to set
A[i][POSITION] = CARD_VALUE
Meaning that after i-th shuffle, card CARD_VALUE is in position POSITION. I don't want to give you all the specifics, but it will take another for loop, and the nested for-loop for printing needs to be independent of any other loop, occuring when everything else is done.
Looks like you have a few things concerning the for-loops that you need to look over carefully. Trace the program flow manually or with a debugger and you'll notice that some of those braces and code blocks need to be moved.
--TRY THIS--
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) { //initialize a to all zeroes
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
}
}
for(int i = 0; i < N; i++) //puts the deck in order, shuffles it, and records. N times
{
for (int j = 0; j < M; j++) //order the deck
deck[j] = j;
for(int j = 0; j < M; j++) { //shuffle the deck (same as yours except counter name)
int r = j + (int)(Math.random() * (M-j));
int t = deck[r];
deck[r] = deck[j];
deck[j] = t;
}
for(int j = 0; j < M; j++) //record status of this deck as described
{
int card_at_j = deck[j]; //value of card in position j
a[card_at_j][j]++; //tally that card_at_j occured in position j
}
} //big loop ended
for (int b = 0; b < M; b++) //print loop. a is MxM, so limit of N was wrong.
{
for (int c = 0; c < M; c++)
{
System.out.print(" " + a[b][c]);
System.out.println();
}
} //print loop ended
} //main() ended
} //class ended

Categories

Resources