Grabbing Input for Your Java Programs - dummies

By Barry A. Burd

The Java code you see below illustrates some pithy issues surrounding the input of data. For one thing, the program gets input from both the keyboard and a disk file. (The program gets a room number from the keyboard. Then the program gets the number of guests in that room from the occupancy file.) To make this happen, this program sports two Scanner declarations: one to declare keyboard and a second to declare diskScanner.

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

import static java.lang.System.out;

public class ShowOneRoomOccupancy {

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

Scanner keyboard = new Scanner(System.in);

Scanner diskScanner = new Scanner(new File("occupancy"));

int whichRoom;

out.print("Which room? ");

whichRoom = keyboard.nextInt();

for (int roomNum = 0; roomNum < whichRoom; roomNum++) {

diskScanner.nextInt();

}

out.print("Room ");

out.print(whichRoom);

out.print(" has ");

out.print(diskScanner.nextInt());

out.println(" guest(s).");

keyboard.close();

diskScanner.close();

}

}

Later in the program, the call keyboard.nextInt reads from the keyboard, and diskScanner.nextInt reads from the file. Within the program, you can read from the keyboard or the disk as many times as you want. You can even intermingle the calls — reading once from the keyboard, and then three times from the disk, and then twice from the keyboard, and so on. All you have to do is remember to use keyboard whenever you read from the keyboard and use diskScanner whenever you read from the disk.

Another interesting tidbit concerns the number of files you keep on your computer. In real life, having several copies of a data file can be dangerous. You can modify one copy and then accidentally read out-of-date data from a different copy. Sure, you should have backup copies, but you should have only one “master” copy — the copy from which all programs get the same input.

In a real-life program, you don’t copy the occupancy file from one project to another. What do you do instead? You put an occupancy file in one place on your hard drive and then have each program refer to the file using the names of the file’s directories. For example, if your occupancy file is in the c:\Oct\22 directory, you write

Scanner diskScanner = new Scanner(new File("c:\\oct\\22\\occupancy"));