Program with Disk Input

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Yes.

Program with Disk Input

Here is the program that matches the previous picture. It is nearly the same as a previous example program except for the parts in blue.

import java.util.Scanner;
import java.io.*;

class EchoSquareDisk
{
  public static void main (String[] args) throws IOException
  { 
    File    file = new File("myData.txt");   // create a File object
    Scanner scan = new Scanner( file );      // connect a Scanner to the file
    int num, square;

    num = scan.nextInt();
    square = num * num ;   

    System.out.println("The square of " + num + " is " + square);
  }
}

The program reads its data from myData.txt, a text file that might have been created with a text editor. The file starts with an integer in character format. Here is an example of what the input file might contain:

12

There can be spaces before or after the 12. The Scanner scans over the beginning spaces until it finds characters that can be converted to int. It stops scanning when it encounters the first space after the digits it is converting. If there are additional characters in the file this program ignores them.

QUESTION 4:

Is it possible that the file myData.txt might not exist?