I'm still new in Java, and I'm learning in Bluej for class. My class is doing a small fun program to learn, and I'm wondering... How can I make the program go through the script (or restart) itself? Sorry if you get this a lot, but I've been looking for over an hour for the answer with no success. I still need it for a few other programs as well lol
Here's the code:
import java.util.Scanner;
public class TriangleFirst
{
public static void main (String [] args) {
System.out.println ("\f");
Scanner SC = new Scanner(System.in);
int numbstars;
System.out.println ("How large would you like your (sideways) pyramid to be? (insert a number)");
numbstars = SC.nextInt();
for (int i=1; i<= numbstars; i++) {
for (int j=0; j < i; j++) {
System.out.print ("*");
}
//generate a new line
System.out.println ("");
}
for (int i= numbstars-1; i>=0; i--) {
for (int j=0; j < i; j++) {
System.out.print ("*");
}
//generate a new line
System.out.println ("");
}
}
}
The idea here is to do something over and over again until you are told otherwise. You are already exposed to this idea in
for
loops.while
loops are another kind of loop to know about. Awhile
loop is defined something like so:It will execute all of the code inside it over and over again until you force it to stop via
break;
or the condition isfalse
(changing a Boolean, a number goes below 0, what ever you make your condition). A more advance form of awhile
loop is thedo while
loop. Ado while
looks something like this:The difference here is that a
do while
will always execute once. After that it will evaluate the condition before deciding whether to run again or not. A while loop may never execute! It all depends on the condition.Now, for your condition, you can do a method call. So:
or even
(Note,
while
works the same way.)No matter what the end result should be a Boolean. Your star printing and user input for number of stars can be separate method calls (and generally it's a good idea to separate logic into method calls to make debugging easier). So...
}
should give you a good idea of how to implement it.