我可以问一个关于我头衔的问题。由于我是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);
}
}
答案 0 :(得分:3)
Integer.parseInt(input);
此声明在您的try块 之外。它必须在里面,以便你的程序跳转到catch(NumberFormatException e)
块。
答案 1 :(得分:1)
公共类TestRandomArray {
loginPoints
}
答案 2 :(得分:0)
请仅进行以下更改,有效,
int choosenIndex = 0;
do {
String input = JOptionPane.showInputDialog(null, "Enter index"); //Get input from user
try {
choosenIndex = Integer.parseInt(input); //change the string to int type.
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(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Only integer allowed.");//display other error occured.
}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.
}
}
} while (true);