Solutions to the Try It Out Exercises in Beginning Programming with Java For Dummies, 5th Edition
by Barry Burd

Chapter 13: Piles of Files: Dealing with Information Overload

In this chapter:

Where's my file?

When you execute new Scanner(new File("data.txt")), you're trying to read from a file named data.txt but you haven't yet created a file named data.txt. Java can't find the file to read from, so the program crashes.

Random numbers in a file

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Random;
import java.util.Scanner;

class RandomNumbers {

    public static void main(String args[]) throws FileNotFoundException {
        Random random = new Random();
        PrintStream diskWriter = new PrintStream("randomNumbers.txt");

        int i = 1;
        while (i <= 10) {
            diskWriter.println(random.nextInt());
            i++;
        }
        
        diskWriter.close();
    
        Scanner diskScanner = new Scanner(new File("randomNumbers.txt"));
       
        i = 1;
        while (i <= 10) {
            System.out.println(diskScanner.nextInt());
            i++;
        }
        
        diskScanner.close();
    }
}