Loop the program until 0(exit)(java)

I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:

public class xtree {

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(in);
        out.print("please enter a number: ");
        int temp = scan.nextInt();
        int x = (temp-1)*2 +1; 
        int y = x/2;  
        int z = 1;  
        for(int i=0; i<temp-1; i++) 
        {
            for(int j=0; j<=y; j++) 
            {
                out.print(" ");
            }
            for(int k = 0; k<z; k++) 
            {
                out.print("*");
            }
            out.println(); 
            y--;
            z+=2; 
        }
        for(int i =0; i<=x/2; i++) 
        {
            out.print(" ");
        }
        out.println("*"); 
    }
}

Thank you, im a beginner to java so please be lenient ;)

Jon Skeet
people
quotationmark

Well, I would separate the method out into two:

  • A printChristmasTree method, which accepts the height as a parameter
  • Your main method, which just deals with taking user input and calling printChristmasTree or exiting

Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:

public static void main(String[] args) {
    Scanner scan = new Scanner(in);
    while (true) {
        System.out.print("Please enter a number (0-40): ");
        int height = scan.nextInt();
        if (height == 0) {
            // Exit the program
            return;
        } else if (height >= 1 && height <= 40) {
            printChristmasTree(height);
        } else {
            System.out.println("Invalid input.");
        }
    }
}

There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.

The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.

people

See more on this question at Stackoverflow