简体   繁体   中英

Making Tree with Nested Loops

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM