go to previous page   go to home page   go to next page

Answer:

Yes.


Program with Disk Input

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);
  }
}

This program reads its data from myData.txt, a text file. 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 spaces until it finds characters that can be converted to int. It stops scanning when it encounters the first space after the digits. Any additional characters in the file are ignored.

If there are non-space characters before the "12" the program will throw an Exception . Because of this the main() method must declare

throws IOException

QUESTION 4:

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