-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPS_03_KeepAccessingAnArray.java
More file actions
50 lines (48 loc) · 1.52 KB
/
PS_03_KeepAccessingAnArray.java
File metadata and controls
50 lines (48 loc) · 1.52 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
import java.util.Scanner;
class MaxRetriesExceededException extends Exception{
@Override
public String toString(){
return "\nMaxRetriesExceededException: "+getMessage();
}
@Override
public String getMessage(){
return "You have exceeded the maximum limit of 5 attempts to access the array.";
}
}
public class PS_03_KeepAccessingAnArray {
static void accessArray()throws MaxRetriesExceededException{
// declaration
int index,c = 1;
String [] vegetables = {"Potato","Garlic","Ginger","Tomato","Onion"};
boolean isIndexValid;
do {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an index number - ");
index = sc.nextInt();
try{
System.out.print("Element at index "+index+" - "+vegetables[index]);
isIndexValid = true;
sc.close();
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Invalid Index.\n\tTry again");
isIndexValid = false;
}
if (isIndexValid==true)
break;
else if(c==5){
sc.close();
throw new MaxRetriesExceededException();
}
c++;
}while(c<=5);
}
public static void main(String[] args) {
try{
accessArray();
}
catch(MaxRetriesExceededException m){
// m.printStackTrace();
}
}
}