Question: Please answer and explain each step, keep it simple do not use AI . File ParseInts.java contains a program that does the following: Prompts for
Please answer and explain each step, keep it simple do not use AI 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
it should print
The sum of the integers on the line is
Try some other inputs as well. Now try a line that contains both integers and other values, eg
We have dogs and 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 its not an integer it doesnt 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
noninteger, so the line above will produce a sum of and the line fish fish will produce a
sum of 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
andcats input should now give a sum of 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 mainString args
int val, sum;
Scanner scan new ScannerSystemin;
String line;
System.out.printlnEnter a line of text";
Scanner scanLine new ScannerscannextLine;
while scanLinehasNext
val Integer.parseIntscanLinenext;
sum val;
System.out.printlnThe sum of the integers on this line is
sum;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
