Yes.
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.
Is it possible that the file myData.txt
might not exist?