How to Add Searching Capability with Java

By Barry A. Burd

You’re sitting behind the desk at the Java Motel. Look! Here comes a party of five. These people want a room, so you need software that checks whether a room is vacant. If one is, the software modifies the GuestList.txt file by replacing the number 0 with the number 5. As luck would have it, the software is on your hard drive. The software is shown here.

import static java.lang.System.out;

import java.util.Scanner;

import java.io.File;

import java.io.IOException;

import java.io.PrintStream;

 

public class FindVacancy {

 

public static void main(String args[]) throws IOException {

int guests[] = new int[10];

int roomNum;

Scanner diskScanner = new Scanner(new File("GuestList.txt"));

for (roomNum = 0; roomNum < 10; roomNum++) {

guests[roomNum] = diskScanner.nextInt();

}

diskScanner.close();

roomNum = 0;

while (roomNum < 10 && guests[roomNum] != 0) {

roomNum++;

}

if (roomNum == 10) {

out.println("Sorry, no v cancy");

} else {

out.print("How many people for room ");

out.print(roomNum);

out.print("? ");

Scanner keyboard = new Scanner(System.in);

guests[roomNum] = keyboard.nextInt();

keyboard.close();

PrintStream listOut = new PrintStream("GuestList.txt");

for (roomNum = 0; roomNum < 10; roomNum++) {

listOut.print(guests[roomNum]);

listOut.print(" ");

}

listOut.close();

}

}

}

The motel starts with two vacant rooms — Rooms 3 and 8. (Remember, the rooms start with Room 0.) The first time that you run the code, the program tells you that Room 3 is vacant and puts five people into the room.

filling a vacancy in java
Filling a vacancy.

The second time you run the code, the program finds the remaining vacant room (Room 8) and puts a party of ten in the room. (What a party!)

filling last vacancy in java
Filling the last vacant room.

The third time you run the code, you have no more vacant rooms. When the program discovers this, it displays the message Sorry, no v cancy, omitting at least one letter in the tradition of all motel neon signs.

java no vacancies
Sorry, Bud. No rooms.

A run of the code writes a brand-new GuestList.txt file. This can be confusing because each Java IDE has its own way of displaying the GuestList.txt file’s content. Some IDEs don’t automatically display the newest GuestList.txt file, so after running the code, you may not immediately see a change. Even if you don’t see a change, consecutive runs change the GuestList.txt file. Poke around within your favorite IDE to find out how to make the IDE refresh the GuestList.txt file’s display.

The condition roomNum < 10 && guests[roomNum] != 0 can be really tricky. If you move things around and write guests[roomNum] != 0 && roomNum < 10, you can get yourself into lots of trouble. For details, see allmycode.com.