Beginning Programming with Java For Dummies
Book image
Explore Book Buy On Amazon
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? ");

<strong>whichRoom = keyboard.nextInt();</strong>

for (int roomNum = 0; <strong>roomNum < whichRoom</strong>; 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"));

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: