public class SumUsersFile
1: import java.util.Scanner;
2: import java.io.File;
3: import java.io.FileNotFoundException;
5: /**
6: * Sum all the numbers from a file named by the user.
7: * @see SumAllFromFile.java
8: *
9: * @author Mark Young (A00000000)
10: */
11: public class SumUsersFile {
13: public static void main(String[] args)
14: throws FileNotFoundException {
15: // added following lines to ask the user for the name of the file
16: Scanner kbd = new Scanner(System.in);
17: System.out.print("\n\n"
18: + "Enter the name of a file and I will sum its numbers: ");
19: String fileName = kbd.nextLine();
20: System.out.println();
22: // create the other variables needed
23: Scanner fin = new Scanner(new File(fileName));
24: int num;
25: int sum = 0;
27: // read all the numbers
28: while (fin.hasNextInt()) {
29: num = fin.nextInt();
30: sum += num;
31: }
32: fin.close();
34: // print their sum
35: System.out.println("\nThe sum of all those numbers is " + sum + ".\n");
36: }
38: }