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

Chapter 16: 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;

public class RandomNumbers {

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

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