Tips for Beginning Java Programmers: How to Decide on a Loop’s Limit at Runtime - dummies

Tips for Beginning Java Programmers: How to Decide on a Loop’s Limit at Runtime

By Barry Burd

Any loops you create in Java can be given a limit at runtime. As the owner of a motel, you may want a more succinct report than this one. “Don’t give me a long list of rooms,” you say. “Just give me the number of guests in Room 3.” To get such a report, you need a slightly smarter program.


import java.util.Scanner;
import static java.lang.System.out;
public class ShowOneRoomOccupancy {
 public static void main(String args[])
      throws FileNotFoundException {
  Scanner keyboard = new Scanner(;
  Scanner diskScanner =
   new Scanner(new File("occupancy"));
  int whichRoom;
  out.print("Which room? ");
  whichRoom = keyboard.nextInt();
  for (int roomNum = 0;
    roomNum < whichRoom; roomNum++){
  out.print("Room ");
  out.print(" has ");
  out.println(" guest(s).");

If this code has a moral, it’s that the number of for loop iterations can vary from one run to another. The loop in this code runs on and on as long as the counting variable roomNum is less than a room number specified by the user.

When the roomNum is the same as the number specified by the user (that is, when roomNum is the same as whichRoom), the computer jumps out of the loop. Then the computer grabs one more int value from the occupancy file and displays that value on the screen.

As you stare at the runs of the program, it’s important to remember the unusual numbering of rooms. Room 3 has two guests because Room 3 is the fourth room in the occupancy file. That’s because the motel’s rooms are numbered 0 through 9.