In: Computer Science
Write a Java program to randomly create an array of 50 double values. Prompt the user to enter an index and prints the corresponding array value. Include exception handling that prevents the program from terminating if an out of range index is entered by the user. (HINT: The exception thrown will be ArrayIndexOutOfBounds)
*Please do it in eclipse and this is java language*
import java.util.*;
public class Main
{
public static void main(String[] args) {
Random r = new Random();//to generating random
number
//creating array with space 50
double d[] = new double[50];
//populating it with 50 random values
for(int i=0;i<50;i++)
d[i] = r.nextDouble();
Scanner sc = new Scanner(System.in);//to read
input
while(true)
{
System.out.print("Enter index
:");
try{
int n= sc.nextInt();
//now displaying value at given
index
System.out.println("Value at index
"+n+" :"+d[n]);
}
catch(Exception e)//catching
Exception
{
System.out.println(e+"\nEnter valid
input\n");
}
}
}
}
output:
Enter index :10
Value at index 10 :0.21727595119603493
Enter index :100
java.lang.ArrayIndexOutOfBoundsException: 100
Enter valid input
Enter index :44
Value at index 44 :0.41482599589828884
Enter index :