Answer to Question #2902 in Java | JSP | JSF for zaara

Question #2902
Write an application that prompt the user to enter a number to use as an array size, and
then attempt to declare an array using the entered size.
Java generates a NegativeArraySizeException if wou attempt to create an array with a
negative size, and a NumberFormatException if you atempt to create an array using a
non-numeric value for the size. Use catch block that executes if the array size is nonnumeric
or negative, displaying a message that indicates the array was not created.
If the array is created successfully, display an appropriate message and then prompt the
user to store values in the array. At the end of your program ask the user to enter the
index of the array to display the element value. Create a catch block that catches the
eventual ArrayIndexOutOfBoundsException, so if the user attempts to access an element
out of the range of the array display the message  Now you have gone so far!! .
Expert's answer
import java.util.*;

public class Arr {
public static void main(String[] args) {
Scanner scan = new Scanner(;
int sz;
int[] arr;
System.out.println("Enter array size");
sz = scan.nextInt();
try {
arr = new int[sz];
} catch (NegativeArraySizeException e) {
System.out.println("Negative size of array");
System.out.println("Array was't created");
} catch (NumberFormatException e) {
System.out.println("Error numeric format");
System.out.println("Array was't created");
.println("Array created succesuful. Enter values in the array");
for (int i = 0; i < sz; i++)
arr[i] = scan.nextInt();
System.out.println("Enter inder");
sz = scan.nextInt();
try {
System.out.println(arr[sz - 1]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error in index");

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

New on Blog