Write a program that creates a small (6-10) array of ints. Display your array elements, all on one line, using a foreach loop. In a try block, prompt the user to enter an index for the array and attempt to print the element with that index. Follow the try block with two catch blocks; one that detects an index out of bounds, and another that catches other bad inputs. See Sample Runs below. Sample Run 1 12 15 24 5 9 16 Enter any index of your array 5 Element at index 5 is 16
Write a program that creates a small (6-10) array of ints. Display your array elements, all on one line, using a foreach loop. In a try block, prompt the user to enter an index for the array and attempt to print the element with that index. Follow the try block with two catch blocks; one that detects an index out of bounds, and another that catches other bad inputs. See Sample Runs below.
Sample Run 1
12 15 24 5 9 16
Enter any index of your array 5
Element at index 5 is 16
Sample Run 2
12 15 24 5 9 16
Enter any index of your array 9
Error. Array index was out of bounds
Sample Run 3
12 15 24 5 9 16
Enter any index of your array three
Bad input. Try again
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Step by step
Solved in 4 steps with 2 images