-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSafeArrayLookup.java
More file actions
65 lines (59 loc) · 2.35 KB
/
SafeArrayLookup.java
File metadata and controls
65 lines (59 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Rahim Siddiq
May 26 2023
ArrayIndexOutOfBoundsException
*/
import java.util.Random;
import java.util.Scanner;
import java.util.InputMismatchException;
public class SafeArrayLookup
{
public static void main(String[] args)
{
// Program variables. Create array to store 100 elements, variable to store index and a boolean for validInput
int[] randomArray = new int[100];
int index = 0;
boolean validInput = false;
// Description of program for the user
System.out.println("========================================================================");
System.out.println("===== Program creates an array of 100 elements with random values ======");
System.out.println("== displays the value of elements in the specified index of the array ==");
System.out.println("========================================================================");
System.out.println();
// Create random object and use a for-loop to populate the elements of randomArray
Random rand = new Random();
for (int i = 0; i < randomArray.length; i++)
{
randomArray[i] = rand.nextInt(100);
}
// Create a new scanner object for user input
Scanner input = new Scanner(System.in);
while (!validInput) // will re-prompt for input if incorrect
{
try
{
System.out.print("Enter a number for index to see it's value [0-99]: ");
index = input.nextInt();
System.out.println("The element found at index " + index + " is: " + randomArray[index]);
// Changes condition to break while loop
validInput = true;
}
// ArrayIndexOutOfBoundsException catches errors if index is out of range
catch(ArrayIndexOutOfBoundsException rangeEx)
{
System.out.println("The number entered is outside the bounds of the index, please try again");
System.out.println();
}
// Catches errors caused by non-integer inputs
catch(InputMismatchException typeEx)
{
System.out.println("You must enter an integer for index number, please try again");
System.out.println();
// Clears scanner buffer of non-int input
input.nextLine();
}
}
// Close the scanner
input.close();
}
}