Fitting the Two Pieces Together

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The following loop will print numStars stars all one one line.

int star = 1;
while ( star <= numStars  )
{
  System.out.print("*");
  star = star + 1;
}

Fitting the Two Pieces Together

Now you have two pieces: (1) the part that loops for the required number of lines and, (2) the part that prints the required number of stars per line. Here is the complete program with the two parts fitted together:

import java.util.Scanner;
//
class StarBlock
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    int numRows;      // the number of Rows
    int numStars;     // the number of stars per row
    int row;          // current row number

    // collect input data from user
    System.out.print( "How many Rows? " );
    numRows = scan.nextInt() ;

    System.out.print( "How many Stars per Row? " );
    numStars = scan.nextInt() ;

    row  =  1;
    while ( row <= numRows )    
    {
      int 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.

QUESTION 22:

What would the program do if the user asked for a negative number of stars per line?