Write an application that prompts the user to enter a number to use as an array
ID: 651164 • Letter: W
Question
Write an application that prompts the user to enter a number to use as an array size, and then attemp to declare an array using the entered size. If the array is created successfully, display an appropriate message. Java generates a NegativeArraySizeException if you attempt to create an array with a negative size, and it creates a NumberFormatException if you attemp to create an array using a nonnumeric value for the size. Use a catch block that executes if the array size is nonnumeric or negative, display a message that indicates the array was not created. Class should be NegativeArray.
Should be written in java.
Please follow directions.
Explanation / Answer
Required solution:
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();
}
}
}
sample output:
TestCase:1
Enter the size of the array:-9
Array was not created
TestCase:2
Enter the size of the array:abc
Array was not created
TestCase:3
Enter the size of the array:14
Array was created
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.