Question

Placing Exception Handlers File ParseInts.java contains a program that does the following: Prompts for and reads...

  1. Placing Exception Handlers

File ParseInts.java contains a program that does the following:

  • Prompts for and reads in a line of input
  • Uses a second Scanner to take the input line one token at a time and parses an integer from each token as it is extracted.
  • Sums the integers.
  • Prints the sum.

Save ParseInts to your directory and compile and run it. If you give it the input

10 20 30 40

it should print

The sum of the integers on the line is 100.

Try some other inputs as well. Now try a line that contains both integers and other values, e.g.,

We have 2 dogs and 1 cat.

You should get a NumberFormatException when it tries to call Integer.parseInt on “We”, which is not an

integer. One way around this is to put the loop that reads inside a try and catch the NumberFormatException but not do anything with it. This way if it’s not an integer it doesn’t cause an error; it goes to the exception handler, which does nothing. Do this as follows:

  • Modify the program to add a try statement that encompasses the entire while loop. The try and opening { should go before the while, and the catch after the loop body. Catch a NumberFormatException and have an empty body for the catch.
  • Compile and run the program and enter a line with mixed integers and other values. You should find that it stops summing at the first non-integer, so the line above will produce a sum of 0, and the line “1 fish 2 fish” will produce a sum of 1. This is because the entire loop is inside the try, so when an exception is thrown the loop is terminated. To make it continue, move the try and catch inside the loop. Now when an exception is thrown, the next statement is the next iteration of the loop, so the entire line is processed. The dogs-and-cats input should now give a sum of 3, as should the fish input.

// ****************************************************************

// ParseInts.java

//

// Reads a line of text and prints the integers in the line.

//

// ****************************************************************

import java.util.Scanner;

public class ParseInts

{

public static void main(String[] args)

{

int val, sum=0;

Scanner scan = new Scanner(System.in);

String line;

System.out.println("Enter a line of text");

Scanner scanLine = new Scanner(scan.nextLine());

while (scanLine.hasNext())

{

val = Integer.parseInt(scanLine.next());

sum += val;

}

System.out.println("The sum of the integers on this line is " +

sum);

}

}

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

//****************************************************************

//ParseInts.java

//

//Reads a line of text and prints the integers in the line.

//

//****************************************************************

import java.util.Scanner;

public class ParseInts {
  
   public static void main(String[] args)
   {
  
       int val, sum=0;
  
       Scanner scan = new Scanner(System.in);
  
       String line;
  
       System.out.println("Enter a line of text");
  
       Scanner scanLine = new Scanner(scan.nextLine());
      
           while (scanLine.hasNext())
      
           {
      
           val = Integer.parseInt(scanLine.next());
      
           sum += val;
      
           }
      
  
       System.out.println("The sum of the integers on this line is " +
  
       sum);

   }

}

//end of program

Output:

//****************************************************************

//ParseInts.java

// Modification 1

//Reads a line of text and prints the integers in the line.

// Modified program to catch NumberFormatException

//****************************************************************

import java.util.Scanner;

public class ParseInts {
  
   public static void main(String[] args)
   {
  
       int val, sum=0;
  
       Scanner scan = new Scanner(System.in);
  
       String line;
  
       System.out.println("Enter a line of text");
  
       Scanner scanLine = new Scanner(scan.nextLine());
       // try-catch block to catch the NumberFormatException
       // but now the process stops when it encounters a non-integer data
       // as the control reached the catch block which is outside the while
       try {
           while (scanLine.hasNext())
      
           {
      
           val = Integer.parseInt(scanLine.next());
      
           sum += val;
      
           }
       }catch(NumberFormatException e)
       {
          
       }
  
       System.out.println("The sum of the integers on this line is " +
  
       sum);

   }

}

//end of program

Output:

//****************************************************************

//ParseInts.java

// Modification 2

//Reads a line of text and prints the integers in the line.

// Modified ParseInts to catch the NumberFormatException but continue processing until the entire line has been read

//****************************************************************

import java.util.Scanner;

public class ParseInts {
  
   public static void main(String[] args)
   {
  
       int val, sum=0;
  
       Scanner scan = new Scanner(System.in);
  
       String line;
  
       System.out.println("Enter a line of text");
  
       Scanner scanLine = new Scanner(scan.nextLine());

       while (scanLine.hasNext())
           {
               // try-catch block to catch the NumberFormatException
               // when non-integer data is encountered, the control goes
               // to the catch block but processing continues as the try-catch block is within the loop
               // so the process continues till we reach end of the input line
               // and hence it calculates the sum of all integers in the input line
               try {
                   val = Integer.parseInt(scanLine.next());
                   sum += val;
               }catch(NumberFormatException e)
               {
                  
               }
           }
      
  
       System.out.println("The sum of the integers on this line is " +
  
       sum);

   }

}

//end of program

Output:

Add a comment
Know the answer?
Add Answer to:
Placing Exception Handlers File ParseInts.java contains a program that does the following: Prompts for and reads...
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
  • Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written...

    Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written to a file. Each line of the input file will contain the student name (a single String with no spaces), the number of semester hours earned (an integer), the total quality points earned (a double). The following shows part of a typical...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Select the correct answer. (1)     Which of the following will open a file named MyFile.txt and...

    Select the correct answer. (1)     Which of the following will open a file named MyFile.txt and allow you to read data from it?                (a)      File file = new File("MyFile.txt");           (b)      FileWriter inputFile = new FileWriter();           (c)       File file = new File("MyFile.txt");                      FileReader inputFile = new FileReader(file);           (d)      FileWriter inputFile = new FileWriter("MyFile.txt"); (2)     How many times will the following do - while loop be executed?                      int x = 11;             do {             x...

  • 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);        } } /* In the first program, the Scanner may throw an...

  • Question 1 (5 points) Question 1 Unsaved What is displayed on the console when running the...

    Question 1 (5 points) Question 1 Unsaved What is displayed on the console when running the following program? public class Quiz2B { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } } Question 1 options: The program displays Welcome to Java two times. The program displays Welcome to...

  • Hi. This is a prototype of Java. The following Java program was developed for prototyping a...

    Hi. This is a prototype of Java. The following Java program was developed for prototyping a mini calculator. Run the program and provide your feedback as the user/project sponsor. (Save the code as MiniCalculator.java; compile the file: javac MiniCalculator.java; and then run the program: java MiniCalculator). HINTs: May give feedback to the data type and operations handled by the program, the way the program to get numbers and operators, the way the calculation results are output, the termination of the...

  • In Java - Write a program that prompts the user to enter two integers and displays...

    In Java - Write a program that prompts the user to enter two integers and displays their sum. If the input is incorrect, prompt the user again. This means that you will have a try-catch inside a loop.

  • Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly...

    Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly below): //Create public class count public class Count {     public static void main(String args[])     {         int n = getInt("Please enter an integer value greater than or equal to 0");                System.out.println("Should count down to 1");         countDown(n);                System.out.println();         System.out.println("Should count up from 1");         countUp(n);     }            private static void countUp(int n)     {...

  • Write a program that reads a file containing an arbitrary number of text integers that are...

    Write a program that reads a file containing an arbitrary number of text integers that are in the range 0 to 99 and counts how many fall into each of eleven ranges. The ranges are 0-9, 10-19, 20-29,..., 90-99 and an eleventh range for "out of range." Each range will correspond to a cell of an array of ints. Find the correct cell for each input integer using integer division. After reading in the file and counting the integers, write...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

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