The following loop will print numStars
stars all one one line.
star = 1; while ( star <= numStars ) { System.out.print("*"); star = star + 1; }
So.... now you have two pieces: (1) the part that ensures that the required number of lines "happen," and, (2) the part that prints the required number of stars per line. Here is a complete program, the two parts fitted together:
import java.io.*; // User picks ending value for time, t. // The program calculates and prints the distance the brick has fallen for each t. // class starBlock { public static void main (String[] args ) throws IOException { int numRows; // the number of Rows int numStars; // the number of stars per row int row ; // current row number int star; // the number of stars in this row so far BufferedReader userin = new BufferedReader (new InputStreamReader(System.in)); String inputData; // collect input data from user System.out.println( "How many Rows?" ); inputData = userin.readLine(); numRows = Integer.parseInt( inputData ); System.out.println( "How many Stars per Row?" ); inputData = userin.readLine(); numStars = Integer.parseInt( inputData ); row = 1; while ( row <= numRows ) { star = 1; while ( star <= numStars ) { System.out.print("*"); star = star + 1; } System.out.println(); // need to do this to end each line row = row + 1; } } }
The part concerned with printing the right number of stars per line is
in blue.
Notice how one while
loop is in the body of the other loop.
This is an example of nested loops.
The loop that is in the body of the other is called the inner loop.
The other is called the outer loop.