I need help with creating a Java program. Please read the instructions. A basic
ID: 3808465 • Letter: I
Question
I need help with creating a Java program. Please read the instructions. A basic and simple code would be appreciated.
Write a program that meets the following requirements:
Creates an array with 100 randomly chosen integers, between 1 and 1000. (Refer to pg. 87 for instructions on generating random numbers.)
Prompts the user to enter the index of the array, then displays the corresponding element value. If the specified index is out of bounds, display the message “Out of Bounds” and will print the ArrayIndexOutOfBoundsException object.
Use the Exception class, ArrayIndexOutOfBoundsException. You will need to import java.lang.ArrayIndexOutOfBoundsException; The ArrayIndexOutOfBoundsException will keep track of the bad index.
Sample run:
Enter an index: 500
Index out of bound
java.lang.ArrayIndexOutOfBoundsException: 500
Press any key to continue . . .
*You must use exception handling in your solution.
Explanation / Answer
ArrayIndexExpTest.java
import java.util.Random;
import java.util.Scanner;
public class ArrayIndexExpTest {
public static void main(String[] args) {
int a[] = new int[100];
Random r = new Random();
for(int i=0; i<a.length; i++){
a[i] = r.nextInt(1000)+1;
}
try{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an index: ");
int index = scan.nextInt();
System.out.println("Value at index is "+a[index]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Index out of bound");
System.out.println(e.getClass().getName()+": "+e.getMessage());
}
}
}
Output:
Enter an index: 500
Index out of bound
java.lang.ArrayIndexOutOfBoundsException: 500
Enter an index: 50
Value at index is 482
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.