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)
import java.util.InputMismatchException; import java.util.Scanner; public class RandomDouble { public static void main(String[] args) { Scanner in = new Scanner(System.in); double[] numbers = new double[50]; for (int i = 0; i < numbers.length; i++) { numbers[i] = Math.random(); } try { System.out.print("Enter a valid index from 0-49: "); int index = in.nextInt(); System.out.println("Array value of index " + index + " is " + numbers[index]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid index"); } catch (InputMismatchException e) { System.out.println("You did not enter an integer for index"); } } }
Get Answers For Free
Most questions answered within 1 hours.