Write a program that does the following: 1. Prompt the User for 10 integers. 2.
ID: 3666726 • Letter: W
Question
Write a program that does the following:
1. Prompt the User for 10 integers.
2. Read each integer as a string.
3. Use the parseInt method to convert each string as it is entered into an integer.
If the input is not valid (ie: not an integer) a NumberFormatException will be thrown when you try to convert it from string to integer. If this exception is thrown:
1. Print an appropriate error message letting the User know that the input is not an integer.
2. Recover from the error by allowing the loop to continue until all 10 numbers are entered and all are valid.
DO NOT exit the loop if an invalid number is entered. Once the loop is started it must finish - the exception handling you incorporate should allow the program to recover from the exception and continue on to finish the loop.
Explanation / Answer
Answer -
import java.util.*;
import java.lang.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
String num;
int i=1;
int[] number=new int[11];
Scanner console = new Scanner (System.in);
do
{
System.out.print(" Enter Integer "+i+" :");
num = console.nextLine();
try
{
number[i] = Integer.parseInt(num);
}
catch(NumberFormatException nfe)
{
System.err.println(" input is not an integer!! Enter again!");
continue;
}
i++;
}while(i<11);
for(int j=1;j<11;j++)
{
System.out.print(" Integer "+number[j]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.