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.
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 {
} // 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.
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. |