Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads all the numbers from the file mynums.dat and prints o

ID: 3575096 • Letter: W

Question

Write a program that reads all the numbers from the file mynums.dat and prints out the sum of the positive values from the file. You must output an error if the file can't be opened or contains any non-numeric values. You must write the complete program and the output when the program is run successfully must conform exactly to the sample output.

sample run The positives sum to 251.650 import java.io.File; import java. io.FileNotFoundException; import java. util.InputMismatchException; import java. util.Scanner; public class Findsum public static void main(String[] args)

Explanation / Answer

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FindSum {

   /**
   * @param args
   */
   public static void main(String[] args) {

       Scanner scanner = null;
       try {
           File file = new File("mynums.dat");
           if (!file.exists())
               throw new FileNotFoundException();
           scanner = new Scanner(file);
           int sum = 0, n;
           while (scanner.hasNext()) {
               String word = scanner.next();
               try {
                   n = Integer.parseInt(word);
                   if (n > 0)
                       sum += n;

               } catch (NumberFormatException e) {
                   // TODO: handle exception
                   System.out.println("Invalid input :" + word);
               }

           }
           System.out.println("The Sum of positive values is :" + sum);
       } catch (FileNotFoundException e) {
           // TODO: handle exception
           System.out.println("");
       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       }
   }
}

mynums.dat

3
45
6
-2
o
op
3

OUTPUT:

Invalid input :o
Invalid input :op
The Sum of positive values is :57

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote