15-100 Lecture 9 (Monday, September 18, 2006)

break

What happens if we want to end a loop "early", without returning to the predicate? A "break" statement exists for this purpose. If a "break" occurs within a loop, the loop immediately ends. The code within the loop, after the break, does not get executed. And, the loop doesn't start over. It just ends. The flow of control picks up right after the loop.

Please consider the following typical example:

  String userInput;

  while (true) {
    System.out.println ("Enter the next number, or a Q to quit.");
    userInput = keyboard.next();

    if (userInput.equals("Q"))
      break;

    System.out.println ("You entered: " + userInput);
  }

  System.out.println ("Thanks for playing!");
  

Notice how the break allowed us to test a condition within the loop. It can also be combined with a predicate:

  System.out.println ("Please enter up to 10 numbers or a Q to quit");
 
  for (int number=0; number <=10; number++) {
    System.out.print ("Enter number" + number + ": ");

    String userInput = keyboard.next();

    if (userInput.equals("Q"))
      break;

    System.out.println ("For number" + number + ", you entered: " + userInput);
  }

  System.out.println ("Thanks for playing!");
  

continue

The break statement, as described above, immediately takes the flow of control out of a loop. By contrast, the continue statement causes the flow of control to go immediately back to the "top" of the loop, where the predicate is evaluated. If a continue is reached, the subsequent code is not executed, the increment of a for loop doesn't occur. Instead, "without passing go or collecting $500", control returns immediately to the top of the loop.

Please consider the example below:

  System.out.println ("Please enter five numbers between 1 and 10...");

  for (int count=0; count <= 5; count++) {
    System.out.print ("Please enter number " + count + ": ");
   
    int number = keyboard.nextInt();

    // Note: This may be the first time you've seen ||
    // it means logical OR, in other words either-or, or at least one
    if ( (number < 1) || (number > 10) ) {
      System.out.println ("" + number + " isn't between 1 and 10, inclusive.");
      continue; // Back to the top, the "count" control variable will be unchanged
    }

    System.out.println ("Number " + count + " is " + number + ".");

    
  }
  

Scope

Scope is something we talked about briefly. This has to do with the range in which certain variables exist. For example, if we have:

    String s;
    if(true){
      String t;
    }
  

The String s exists everywhere inside the method that contains this code, including the if statement. String t, however, exists only within the if statement, so if you tried to say 't = "Hello";' after the if statement, it would spit out a compile error that says it 't' may not have been declared. We'll go over this more later.