Question

In: Computer Science

Find the readData() method Inside this method is a try block without any catch statements. Add...

  1. Find the readData() method
  2. Inside this method is a try block without any catch statements. Add the following 5 catch statements to this file (Hint: put them in the right order):
    1. RuntimeException
    2. Exception
    3. FileNotFoundException
    4. NumberFormatException
    5. InputMismatchException
  3. For each of these print out a short message describing the exception that occurred

Java Class

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

public class ReadInData {

   public static double readData(String fileName) {
       File file = new File(fileName);
       Scanner scan;
       double sum = 0;
       try {
           scan = new Scanner(file);
           int numOfValues = Integer.parseInt(scan.nextLine()); // Read in Val for # values
           for(int i = 0; i < numOfValues; i++) { // for-loop to get that many values
               sum += scan.nextDouble(); // add the values together (doubles)
           }
           scan.close();
           return sum; // return the sum of all the values in the file
       }//add catch statements here      
   }

   public static void main(String[] args) {
       System.out.println(readData("Test3.txt"));
       System.out.println(readData("Test2.txt"));
       System.out.println(readData("Text4.txt")); // notice spelling of the file name!
       System.out.println(readData("Test4.txt"));
   }

}

Test2.txt

6
5
3.0
"9.8"
-19.8
-54.1
85.5

Test3.txt

4.0
5.0
6.2
4.2
1.0

Test4.txt

5
4.2
3.1
2.2
6.1

Solutions

Expert Solution

HELLO I AM ADDING CODE HERE
WITH OUTPUT

PLEASE GO THROUGH IT
THANK YOU

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

public class ReadInData{

   public static double readData(String fileName) {
       File file = new File(fileName);
       Scanner scan;
       double sum = 0;
       try {
           scan = new Scanner(file);
           int numOfValues = Integer.parseInt(scan.nextLine()); // Read in Val for # values
           for(int i = 0; i < numOfValues; i++) { // for-loop to get that many values
               sum += scan.nextDouble(); // add the values together (doubles)
           }
           scan.close();
     }//add catch statements here 
     catch(FileNotFoundException ex)
     {
       System.out.println("Provided file not found");
     }
     catch(NumberFormatException ex)
     {
       System.out.println("Format of the number is not correct");
     }
     catch(InputMismatchException ex)
     {
       System.out.println("Hey Input is not matching correctly");
     }
     catch(RuntimeException ex)
     {
       System.out.println("Runtime exception occured ");
     }
     catch(Exception ex)
     {
       System.out.println("Hey something went wrong! Not able to find it ");
     }
     return sum;
   }

   public static void main(String[] args) {
       System.out.println(readData("Test3.txt"));
       System.out.println(readData("Test2.txt"));
       System.out.println(readData("Text4.txt")); // notice spelling of the file name!
       System.out.println(readData("Test4.txt"));
   }

}

OUTPUT


Related Solutions

Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
For practice using exceptions, this exercise will use a try/catch block to validate integer input from...
For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner...
(20 pts) In the following code inside a try block, what kind of object is passed...
(20 pts) In the following code inside a try block, what kind of object is passed to the Scanner constructor? Scanner file = new Scanner ( new File (“test.txt”)); (20 pts) What is the output of this code sequence? Scanner parse = new Scanner (“A 1 B 2 C 3 D”); while (parse.hasNext())     System.out.print(parse.next()); (20 pts) What is wrong with following code? try { Scanner file = new Scanner(new File(“c:\docs\data.txt”)); int n = 0; while (file.hasNext()) { String s...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally structure may also have a “throws” declaration. b) An arithmetic exception such as division by zero can be avoided by careful programming while an I/O exception such as file not found may occur regardless of the precautions taken by the programmer. c) Lets assume that you create an object x of the Object class. You can assign any object (objects of other classes) to...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc or VS2017) when an input is invalid (i.e., no data, wrong format, wrong type, etc.) and fails the type conversion. Generate random integers from any of the following three non-overlapped ranges -14 ~ -7 -2 ~ 5 33 ~ 44 Numbers generated must also randomly distributed across the three ranges.
Using Python In this assignment we will try to add tuples, lists, if statements and strings...
Using Python In this assignment we will try to add tuples, lists, if statements and strings to our program. For example, you can ask for a user for a couple items, their name and age – and depending on their age, print out a predefined list. You could ask for some string input and decide to do something with the output. You could ask for three items, 1) age, 2) are you a male or female and 3) are your...
1. Will the vessel of water with a floating block weigh any more than without the...
1. Will the vessel of water with a floating block weigh any more than without the block? If so, how much? Explain 2. Assume a can is completely filled and preparations are ready for catching the overflow water. A block, which will float, is now carefully placed in the can and the overflow water is caught and measured. The experiment is then repeated with gasoline in the can. Discuss the relative volumes and weights of the two overflow liquids. 3....
Allow the InsertAt method to add to the front position 0 (zero) also if you try...
Allow the InsertAt method to add to the front position 0 (zero) also if you try to add to a position greater than the number of nodes you get an error warning. Please do through this order. Thanks --> I need you to add more than 2 front position. // 1 LOAD THE LIST FROM DATA.BIN //buildlist // 2 DISPLAY THE LIST //prntlist // 3 ADD TO THE LIST // listinsert // 4 DELETE FROM THE LIST // listdelete //...
Find a receipt from any purchase you made, and try to represent it in a Java...
Find a receipt from any purchase you made, and try to represent it in a Java program. Make sure to use the most appropriate data type for each of these items List all items purchased Price of each item Subtotal Total Tax (if any) Total (Subtotal + tax) Any company information at the bottom or top of receipt as well
Exercise 2. Automate the boring stuff, page 77, Input Validation. Add try and except statements to...
Exercise 2. Automate the boring stuff, page 77, Input Validation. Add try and except statements to the previous project to detect whether the user types in a noninteger string. Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy'). In the except clause, print a message to the user saying they must enter an integer. THis is the previous project #function definition def collatzSequence(number): # if number % 2 == 0:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT