Assignemnt #128 Summing Several Numbers from Any File
Code
import java.util.Scanner;
import java.io.File;
public class SummingSeveralNumbers
{
public static void main(String[] args) throws Exception
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Which file would you like to read numbers from: ");
String file = keyboard.next();
System.out.println("Reading from " + file);
System.out.println("");
while (file.equals("4nums.txt") || file.equals("5nums.txt") || file.equals("6nums.txt") || file.equals("7nums.txt"))
{
Scanner reader = new Scanner(new File(file));
int total = 0;
while (reader.hasNext())
{
int a = reader.nextInt();
System.out.print(a + " ");
total = total + a;
}
System.out.println("Total: " + total);
System.out.println("");
System.out.println("Which file would you like to read numbers from next: ");
System.out.print("> ");
file = keyboard.next();
System.out.println("");
}
}
}
Picture of the output