mardi 23 février 2016

Random Numbers and Catching an IndexOutOfBoundsException

So I have been given an assignment to catch an IndexOutOfBoundsException using random numbers in an array, and I'm not sure how to print the random number from the array. Here are the directions for my assignment:

  1. Create an array with 50 randomly chosen integers, between 1 and 50.
  2. Prompt the user for an array index value and display the contents of the array at that index value. Assume that the end-user knows that arrays are indexed from 0, so an input of 0 to 49 would be valid.
  3. Trap the error if the user specifies an index that is out of bounds, and print a Java-generated error message. Re-prompt after the error.

Here is my code so far:

import java.util.Scanner;
import java.util.ArrayList;
public class Lab10b
{
    public static void main (String [] args){
        int[] arr = new int[50];
        for(int i = 0; i < arr.length; i++){
            arr[i] = (int) (Math.random() * 50);
        }

        Scanner scan = new Scanner(System.in);
        System.out.print("Type an array index value:  ");
        int x = scan.nextInt();
        try{
           System.out.println(
        }
        catch(ArrayIndexOutOfBoundsException e){
           System.out.println("That index does not exist.");
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire