Page 168 - Introduction to Programming with Java: A Problem Solving Approach
P. 168

                134 Chapter 4 Control Statements
 /************************************************************
*
NestedLoopRectangle.java
Dean & Dean
This program uses nested looping to draw a rectangle.
*************************************************************/
*
*
*
import java.util.Scanner;
public class NestedLoopRectangle
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int height, width;
char printCharacter;
// rectangle's dimensions
System.out.print("Enter height: ");
height = stdIn.nextInt();
System.out.print("Enter width: ");
width = stdIn.nextInt();
System.out.print("Enter character: ");
printCharacter = stdIn.next().charAt(0);
        Apago PDF Enhancer
for (int row=1; row<=height; row++)
{
  for (int col=1; col<=width; col++)
  {
}
System.out.print(printCharacter);
 System.out.println();
 }
// end class NestedLoopRectangle
}
Use print here, to stay on same line.
 Use println here, to move to new line.
 }
// end main
Figure 4.17 Program that uses nested loops to draw a rectangle
Note how we use the print method for the print statement inside the inner loop to keep subsequent printed characters on the same line. Then after the inner loop finishes, we use a separate println method to go to the next line.
For most problems where you’re dealing with a two-dimensional picture like this rectangle example, you’ll want to use nested for loops with index variables named row and col (col is short for column). Why? It makes code more understandable. For example, in the first for loop header, the row variable goes from 1 to 2 to 3, and so on, and that corresponds perfectly with the actual rows printed by the program. However, be aware that it’s also common for nested for loops to use index variables named i and j. Why i and j? Because i stands for “index,” and j comes after i.
























































   166   167   168   169   170