i need help adding this to the following program One thing to add is that the ou
ID: 669197 • Letter: I
Question
i need help adding this to the following program One thing to add is that the output should tell what is the exact reason that it fails to create an array - negative number or wrong number format.
thanks in advance.
import java.util.Scanner;
//NegativeArray class
public class NegativeArray
{
public static void main(String[] args)
{
System.out.print("Enter the size of the array");
Scanner sc=null;
try
{
sc=new Scanner(System.in);
String sizeInput=sc.nextLine();
int size=Integer.parseInt(sizeInput);//may cause NumberFormatException
int[] array=new int[size];//may cause NegativeArraySizeException
System.out.println("Array was created");
}
catch(NegativeArraySizeException e)
{
System.out.println("Array was not created");
}
catch(NumberFormatException e)
{
System.out.println("Array was not created");
}
finally
{
sc.close();
}
}
}
Explanation / Answer
when ever you are entering a negative number as an input then it executing the following line immediatly
"catch(NumberFormatException e)"
this is the reason it fails to catch the negative number.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.