Question

import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {              ...

import java.util.Scanner;

import java.io.File;

public class Exception2 {

       public static void main(String[] args) {

              int total = 0;

              int num = 0;

              File myFile = null;

              Scanner inputFile = null;

              myFile = new File("inFile.txt");

              inputFile = new Scanner(myFile);

              while (inputFile.hasNext()) {

                     num = inputFile.nextInt();

                     total += num;

              }

              System.out.println("The total value is " + total);

       }

}

/*

  1. In the first program, the Scanner may throw an exception due to bad data entry. This is an unchecked exception for which the Java runtime system will handle by aborting the program and displaying the exception information. Other methods may throw checked exceptions. A checked exception must be handled. Type the program (Exception2.java) above and compile. You should receive a compilation error stating that the an particular exception must be caught or declared to be thrown.
  2. So we will test the program knowing that the input file does not exist. Add a try/catch block such that if the input file is not found, report the problem and display a total of 0. Use the getMessage() method of the exception object to report the problem.
  3. Next create an ASCII plain text-based file named inFile.txt using a text editor. Enter only integer values into the file and save the file in the same folder as the program (if you are using a IDE, then put it in the main project folder). Run the program to verify that the program functions correctly with a valid input file.
  4. Any number of catch clauses may be coded for a single try block. Add another catch clause to catch the same exception as in the Exception1 program immediately before or after the file exception clause you just added. Remember to import the exception class and to clear the scanner buffer.
  5. Modify the inFile.txt file to include an error (a non integer value). Run and test the program. As soon as an exception occurs, the catch clause is executed. Since the exception catch clause is outside of the read loop (step 4 above), the first invalid piece of data will cause the program to end without reading the remainder of the file.

Any number of try blocks may be coded with each having a least one catch clause. Rather than catching the data exception outside the loop, move it inside the loop. This will allow the program to report the invalid data, resume processing, and produce correct results for all of the valid data given. Add a new try block within the while loop and remove the exception catch block from Step 4. End result is one try/catch for the file issue and another try/catch for the bad data read by Scanner */

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer 1:


import java.util.Scanner;

import java.io.File;
import java.io.FileNotFoundException;

public class Exception2 {

   public static void main(String[] args) {

       int total = 0;

       int num = 0;

       File myFile = null;

       Scanner inputFile = null;

       myFile = new File("inFile.txt");

       try {
           inputFile = new Scanner(myFile);

           while (inputFile.hasNext()) {

               num = inputFile.nextInt();

               total += num;

           }
       } catch (FileNotFoundException e) {
           System.out.println(e.getMessage());
       }
       System.out.println("The total value is " + total);

   }

}

With Valid File:

With Invalid Data:


import java.util.InputMismatchException;
import java.util.Scanner;

import java.io.File;
import java.io.FileNotFoundException;

public class Exception2 {

   public static void main(String[] args) {

       int total = 0;

       int num = 0;

       File myFile = null;

       Scanner inputFile = null;

       myFile = new File("inFile.txt");

       try {
           inputFile = new Scanner(myFile);

           while (inputFile.hasNext()) {
               num = inputFile.nextInt();
               total += num;

           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (InputMismatchException e) {
           System.out.println(e.getMessage());
       }
       System.out.println("The total value is " + total);

   }

}

Add a comment
Know the answer?
Add Answer to:
import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {              ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Program 2 #include #include using namespace std; int main() { int total = 0; int num...

    Program 2 #include #include using namespace std; int main() { int total = 0; int num = 0; ifstream inputFile; inputFile.open("inFile.txt"); while(!inputFile.eof()) { // until we have reached the end of the file inputFile >> num; total += num; } inputFile.close(); cout << "The total value is " << total << "." << endl; Lab Questions: We should start by activating IO-exceptions. Do so using the same method in Step 3 of the Program 1 assignment above, except that instead...

  • import java.util.Scanner; public class TwelveDays {    public static void main(String[] args)    {       final...

    import java.util.Scanner; public class TwelveDays {    public static void main(String[] args)    {       final int MAX = 12;       int lastDay = 0; //last day for the song, user will update       Scanner scan = new Scanner(System.in);       //Get the last day and use input validation //Begin 1st while       {       }                     int day = 1;      //loop control variable for song verses       //Begin 2nd while       {          //Output: "On the" + day...

  • import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {...

    import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {        String name;        String answer;        int correct = 0;        int incorrect = 0;        Scanner phantom = new Scanner(System.in);        System.out.println("Hello, What is your name?");        name = phantom.nextLine();        System.out.println("Welcome " + name + "!\n");        System.out.println("My name is Danielle Brandt. "            +"This is a quiz program that...

  • import java.util.Scanner; public class MPGMain {    public static void main(String[] args)    {       ...

    import java.util.Scanner; public class MPGMain {    public static void main(String[] args)    {        Scanner input = new Scanner(System.in);               Mileage mileage = new Mileage();               System.out.println("Enter your miles: ");        mileage.setMiles(input.nextDouble());               System.out.println("Enter your gallons: ");        mileage.setGallons(input.nextDouble());               System.out.printf("MPG : %.2f",mileage.getMPG());           } } public class Mileage {    private double miles;    private double gallons;    public double getMiles()...

  • import java.util.Scanner; public class Lab6d { public static void main(String[] args) {    Scanner scnr =...

    import java.util.Scanner; public class Lab6d { public static void main(String[] args) {    Scanner scnr = new Scanner(System.in); // TODO: get user choice    // TODO: call printTable method passing choice as the parameter    } public static void printTable(int stop) { // TODO: print header    // TODO: loop to print table rows up to stop value    } Write a Java program where the main () method prompts the user to select an integer value between 1 and...

  • import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables...

    import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables int creditScore; double loanAmount,interestRate,interestAmount; final double I_a = 5.56,I_b = 6.38,I_c = 7.12,I_d = 9.34,I_e = 12.45,I_f = 0; String instructions = "This program calculates annual interest\n"+"based on a credit score.\n\n"; String output; Scanner input = new Scanner(System.in);// for receiving input from keyboard // get input from user System.out.println(instructions ); System.out.println("Enter the loan amount: $"); loanAmount = input.nextDouble(); System.out.println("Enter the credit score: "); creditScore...

  • Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)...

    Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)    {    Scanner keyboard = new Scanner(System.in); System.out.println("This program an inFix Expression: "); System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): "); String aString = keyboard.nextLine();    while (!aString.equals("!")) {    System.out.println (evaluateinFix(aString));    System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): ");    aString = keyboard.nextLine(); } // end while...

  • //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args )...

    //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args ) { Scanner in = new Scanner( System.in ); LinkedList teamList = new LinkedList(); final int TEAM_SIZE = Integer.valueOf(in.nextLine()); for (int i=0; i<TEAM_SIZE; i++) { String newTeamMember = in.nextLine(); teamList.append(newTeamMember); } while (in.hasNext()) { String removeMember = in.nextLine(); teamList.remove(removeMember); }    System.out.println("FINAL TEAM:"); System.out.println(teamList); in.close(); System.out.print("END OF OUTPUT"); } } =========================================================================================== //PoD import java.util.NoSuchElementException; /** * A listnked list is a sequence of nodes with...

  • import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        //...

    import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle.");        Scanner keyboard = new Scanner(System.in);    int size = keyboard.nextInt();    for (int i = 1; i <= size; i++)    {    for (int j = 0; j < i; j++)    {    System.out.print("*");    }    System.out.println();    }    for (int...

  • This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static...

    This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static void main(String args[]) throws IOException { Scanner inFile = new Scanner(new File(args[0])); Scanner keyboard = new Scanner(System.in);    TwoDArray array = new TwoDArray(inFile); inFile.close(); int numRows = array.getNumRows(); int numCols = array.getNumCols(); int choice;    do { System.out.println(); System.out.println("\t1. Find the number of rows in the 2D array"); System.out.println("\t2. Find the number of columns in the 2D array"); System.out.println("\t3. Find the sum of elements...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT