public void printRect() ;This prints a rectangular grid of stars with width columns and height rows.
This is a problem that can be solved using nested loops. Let's think about how to solve this.
First, you need to know that Java prints like a typewriter. It prints row by row. Once a row has been printed, it can't go back up. This is not like a two-dimensional screen, where you can write at (x,y) locations whereever you feel like.
One idea is to think of a single loop, then figure out how to do the other loop. It's usually easier to start out with the outer loop first.
Here's a start:
public void printGrid() { for ( int i = 0 ; i < height ; i++ ) { // PRINT a row } }This basic loop iterates over each row. There are height of these rows. For each row, we want to print width stars.
But we've already written code to do that! It looks like:
for ( int i = 0 ; i < width ; i++ ) { System.out.print( "*" ) ; } // PRINT newline System.out.println( "" ) ;Let's copy these 5 lines of code (2 are braces) under the comment PRINT a row.
public void printGrid() { for ( int i = 0 ; i < height ; i++ ) { // PRINT a row for ( int i = 0 ; i < width ; i++ ) { System.out.print( "*" ) ; } // PRINT newline System.out.println( "" ) ; } }There is a small problem. We've used i in both locations. This doesn't even compile! Even if it did, it would do the wrong thing.
The solution is to change the looping variables so the inner loop's looping variable isn't the same as the outer loop's looping variable. Just to make it easier to read, we'll name the outer looping variable, row, and the inner looping variable, col.
public void printGrid() { for ( int row = 0 ; row < height ; row++ ) { // PRINT a row for ( int col = 0 ; col < width ; col++ ) { System.out.print( "*" ) ; } // PRINT newline System.out.println( "" ) ; } }Recall that width and height are instance variables.
You can also write one loop. Then, you can write another loop!
With practice reading and writing code, you'll get a feel for when you need to do what.