Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.InputMismatchException;
- import java.util.Scanner;
- class AssignmentOne {
- public static void main(String[] args) throws FileNotFoundException, InputMismatchException {
- File file = new File("Numbers.txt");
- try {
- // Initialize Scanner with file
- Scanner in = new Scanner(file);
- double[] arr = new double[10]; // Initialize array
- Arrays.fill(arr, 0.0); // Fills all the array positions with 0.0
- // Maximum doubles is 10, but we are not sure if the text
- // file has 10 numbers so we use hasNextDouble
- double sum = 0;
- while (in.hasNext()) {
- try {
- sum += in.nextDouble();
- } catch (InputMismatchException e) {
- System.out.println("Found a non-numeric value in the file!");
- in.close();
- return;
- }
- }
- System.out.println(sum);
- in.close();
- } catch (FileNotFoundException e) {
- System.out.println("Cannot find the file Numbers.txt");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement