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

Placing Exception Handlers File ParseInts.java contains a program that does the

ID: 3568723 • Letter: P

Question

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

Explanation / Answer

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{
val = Integer.parseInt(scanLine.next());
sum += val;
}
catch(NumberFormatException ne)
{
  
}
}

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

sum);

}

}

o/p:

Enter a line of text
there are 20 birds and 30 dogs
The sum of the integers on this line is 50