Nested Loops

 

Introduction.  We have now presented all of the major decision and looping structures that we will use for this course.  But as you might expect, from even these relatively simple examples, computer code can quickly grow more complicated.

An Aside.  Theories abound about why some people are able to play many others at chess relatively at the same time.  The strongest player tends to move along in a circle, choosing moves as they go along.  Master ranked players are assumed to be able to

  • look ahead to see likely developments better than others
  • see much more of the board, if not the  whole board at once
  • remember a larger variety of other games where similar things  have happened
  • many things barely require conscious attention

Overall, these master ranked players can be said to be viewing "wholes".

Think about when you first learned to do something like swim.  Remember how disjointed you likely felt?  Eventually, most everything came together and you didn't have to be consciously thinking about so many things in order to get yourself to move.

Think about learning your first computer language.  Ultimately, when you look back at the problems you solved early in the course, they look much easier than they did at the time.

Two of my main goals in this course are to

  1. get you to see code patterns, group things as wholes
  2. be able to problem solve in ways that will work across languages
    1. problem solve beyond specific syntax
    2. know what sorts of things you can do with the code without remembering every little syntactic detail (though it's nice if you do)
    3. be able to think in structured ways
    4. be able to think in classes and objects

Trying to do these kinds of things can make learning other languages much easier.  While not everything can be done in every language, there are an awful lot of commonalities and similar problem solving.

Now I will present an example that has a loop nested inside another loop nested inside and if (expression) else structure.  These sorts of structures turn out to be very common in most coding.  You are also more likely to the value of indenting code segments to help you see overall sections and understand what they contribute to the whole program.

This program will be an applet.  You should call it MatrixDisplay.java.

 

import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JApplet;

public class MatrixDisplay extends JApplet
{

public void init()
{

int numberRows = 0;
int numberColumns = 0;
String strNumberRows;
String strNumberColumns;
int i;
int j;
JTextArea outputArea = new JTextArea();
String errorMessage = "";

strNumberRows = JOptionPane.showInputDialog("How many rows do you want in your matrix?");
strNumberColumns = JOptionPane.showInputDialog("How many columns do you want in your matrix?");

try
{

numberRows = Integer.parseInt(strNumberRows);

}

catch (NumberFormatException nfeInteger)
{

errorMessage = errorMessage + "You need to enter an integer for the number of rows!\n";

}

try
{

numberColumns = Integer.parseInt(strNumberColumns);

}

catch (NumberFormatException nfeInteger)
{

errorMessage = errorMessage + "You need to enter an integer for the number of columns!\n";

}

if (errorMessage != "")
{

JOptionPane.showMessageDialog(null, errorMessage, "Input Errors", JOptionPane.ERROR_MESSAGE);

}
else
{

outputArea.setText("The matrix is displayed below:\n\n");

//  loop for working through the rows
for (i=1; i <= numberRows; i++)
{

//  loop for working through the columns of the matrix
for(j=1; j <= numberColumns; j++)
{

outputArea.append("(" + i + "," + j + ")\t");

} // end for loop for column determination

outputArea.append("\n\n");

} // end for loop for row determination

JOptionPane.showMessageDialog(null, outputArea, "Matrix Display", JOptionPane.INFORMATION_MESSAGE);

} // end else segment based on errorMessage

} // end init( )

} // end MatrixDisplay

 

We do our typical imports, declarations and initializations so I won't discuss these any more.  We do our typical error trapping on the inputs and for the parsing.  We accumulate and error message.  Of greater interest is the if (expression) else block containing the for loops.
  • if the errorMessage isn't blank
    • displays the errorMessage accumulated based on the attempted inputs
    • doesn't execute other code
  • if the errorMessage is blank

    • branches to else segment

      • starts incrementing the rows

        • then increments the columns and goes through all of the columns for each row

        • displays  (rowNumber, columnNumber)  in appropriate place

        • tabs over for each entry in a row

        • appends these to the outputArea

      • puts in two new lines for each new row

      • appends these to the outputArea

    • the showMessageDialog( ) method is used from the JOptionPane class to display the results

Make sure to notice how the loops are nested within the else block. 

The display of a matrix with 4 rows and 6 columns will look like the following..

 

 

Since the size of the applet window is unimportant I am leaving it to you to develop the MatrixDisplay.html.