Assignment #128: Summing Several Numbers from Any File
Code
import java.io.File;
import java.util.Scanner;
public class ArbitrarySum {
public static void main(String[] args) throws Exception {
Scanner input1 = new Scanner(new File("Primes.txt"));
Scanner input2 = new Scanner(new File("Doubles.txt"));
Scanner input3 = new Scanner(new File("Fibonacci.txt"));
Scanner kb = new Scanner(System.in);
int a = 0, x = 0, file;
System.out.println("Which file do you want to get numbers from?");
file = kb.nextInt();
if (file == 1) {
while (input1.hasNextInt()) {
a = input1.nextInt();
System.out.print(a + " ");
x = x + a;
}
}
if (file == 2) {
while (input2.hasNextInt()) {
a = input2.nextInt();
System.out.print(a + " ");
x = x + a;
}
}
if (file == 3) {
while (input3.hasNextInt()) {
a = input3.nextInt();
System.out.print(a + " ");
x = x + a;
}
}
System.out.println();
System.out.println(x);
}
}
Picture of the output