【发布时间】:2015-10-28 09:23:44
【问题描述】:
我可以问一个关于我的标题的问题吗?由于我是 java 新手,我对程序中的异常处理有点困惑。我需要做的是,当用户输入错误的输入时,异常需要循环。对于下面的编码,它只执行 ArrayOutOfBounds 异常。为什么当我输入字符串/符号/十进制值时不执行 FormatNumberException。它仅显示在输出部分,但不在 showMessageDialog 输出中。我尝试使用多个异常处理Catch Multiple Java Exception 并且仍然相同。你能帮我解决这个问题吗?任何答案将不胜感激。对不起我的英语不好。
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);
}
}
【问题讨论】:
标签: java loops exception-handling