80 likes | 187 Vues
This guide explores the concepts of nested loops and sentinel-controlled loops in Java. Nested loops allow iterations within iterations, enabling complex data structures to be processed, as demonstrated by examples of 3x3 matrices using both while and for loops. Additionally, sentinel-controlled loops are crucial for collecting input until a specific condition is met, effectively handling user input. We also address common pitfalls, such as avoiding NumberFormatExceptions through structured error handling. Boost your Java skills with these foundational concepts!
E N D
More on Iteration Overview • Nested Loops • Sentinel-Controlled loop • Avoiding Number Format exception
Nested Loops • One of the statements inside a loop (for, while or do-while) could be another while loop statement – such situation is called Nested Loops. • The following example prints the indices of a 3x3 matrix: public class NestedWhileLoop { public static void main(String[] args) { int i=1,j; while(i<=3) { j=1; while(j<=3) { System.out.print(i+","+j+"\t"); j++; } System.out.println(); i++; } } }
Nested Loops (cont’d) • The following example is a for-loop version of the previous example: public class NestedForLoop { public static void main(String[] args) { int i,j; for (i=1; i<=3; i++) { for (j=1; j<=3; j++) System.out.print(i+","+j+"\t"); System.out.println(); } } }
Nested Loops (cont’d) • The following example prints a table of xy for x from 1 to 10 and y from 1 to 5: public class Table { public static void main(String[] args) { final int COLUMN_WIDTH = 7; for (int x = 1; x <= 10; x++) { for (int y = 1; y <= 5; y++) { int p = (int)Math.pow(x, y); // convert value to string String pstr = "" + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) pstr = " " + pstr; System.out.print(pstr); } System.out.println(); } } }
Sentinel-Controlled Loops • It is a common practice to write loops that repeat until a particular data value is read. Such data value is called Sentinel and the loop is called sentinel-controlled loop. • A problem usually encountered in writing such loop is how to choose the sentinel – What if the sentinel is part of the data? • The following example shows how this may be solved – by choosing the sentinel to be of type character. import java.io.BufferedReader; import java.io.InputStreamReader; public class SentinelLoop { public static void main(String[] args) throws java.io.IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter data (Q to finish):");
Sentinel-Controlled Loops (cont’d) double sum = 0; int count = 0; boolean done = false; while (!done) { String inputLine = stdin.readLine(); if (inputLine.equalsIgnoreCase("Q")) done = true; else { double x = Double.parseDouble(inputLine); sum = sum + x; count++; } } if (count == 0) System.out.println("No data"); else System.out.println("Average = " + sum/count); } }
Avoiding Number Format Exception • If a string that contains non-numeric characters is passed to the methods Integer.parseInt, Double.ParseDouble, etc, they throw NumberFormatException. • This can be solved by enclosing a try-and-catch statement inside a loop. import java.io.BufferedReader; import java.io.InputStreamReader; public class NumberFormat { public static void main(String[] args) throws java.io.IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); boolean inputOk = false; do { try { String inputLine = stdin.readLine(); int n = Integer.parseInt(inputLine.trim()); inputOk = true; } catch(NumberFormatException e) { System.out.println("Input Error. Try again."); } } while (!inputOk); } }