May I ask a question regarding to my title. As I were a new comer in java, I a bit confusing with exception handling in my program. What I need to do is, the exceptions need to loop when the user enter the wrong input. For the below coding, its only execute the ArrayOutOfBounds exception. Why the FormatNumberException does not executed when I enter the string/symbol/decimal values. Its only shown in the output section but not in the showMessageDialog output. I try to use multiple exception handling Catch Multiple Java Exception and still the same. Can you help me with this problem. Any answers will be appreciated. Sorry for my bad English.
public class TestRandomArray {
public static void main(String[] args) {
Random ran = new Random(); // create instant object from class Random.
int array[] =new int[100]; //set an array variable with array size of 100
int maxNumber = 150; //set the limit of the random number to generate
for (int i = 0; i < array.length; i++) {
array[i] = ran.nextInt(maxNumber) + 1; //+1 means that the array number should not contain with 0 value. 1-150.
//System.out.println(array[i]);
}
//for(int i : array){
//System.out.println(i + ","); //this for method is other technique to print the list of array.
//}
do {
String input = JOptionPane.showInputDialog(null, "Enter index"); //Get input from user
int choosenIndex = Integer.parseInt(input); //change the string to int type.
try {
if(choosenIndex >= 0 || choosenIndex <= array.length)
JOptionPane.showMessageDialog(null, "The value of choosen index in the array is : "
+ array[choosenIndex]); //display the choosen index value.
System.exit(0);
}catch (ArrayIndexOutOfBoundsException e){
if (choosenIndex < 0 || choosenIndex > array.length) {
JOptionPane.showMessageDialog(null,
"Index is out of bound. Enter from 0-99"); //display error for indexoutbound.
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Only integer allowed.");//display other error occured.
}
} while (true);
}
}