设有一个整数数组a[10],为其赋值为0到9的值,从键盘输入整数i的值,求a[i]的倒数,注意处理各种异常。发生异常后,根据不同的异常,输出警告。
提示:
需要考虑NumberFormatException、ArrayIndexOutOfBoundsException、ArithmeticException、IOException等多种异常。
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
final int aryLength = 10;
int[] ary = new int[aryLength];
fillAry(ary);
calcDaoshu(getInputFromKeyBoard());
}
private static void calcDaoshu(int value) {
try{
double input = 1/value;
System.out.println(input);
}catch(ArithmeticException arithmeticExp){
JOptionPane.showMessageDialog(null, "Can't be divided by ZERO!");
}
}
private static void fillAry(int[] ary) {
for(int i = 0; i <= ary.length; i++){
try{
ary[i] = i;
}catch(ArrayIndexOutOfBoundsException exp){
JOptionPane.showMessageDialog(null, " Error! Array index out of bounds.");
break;
}
}
}
private static int getInputFromKeyBoard() {
int value = 0;
boolean isDigit = false;
while(!isDigit){
String input = JOptionPane.showInputDialog("Please input a digit number");
try {
value = Integer.parseInt(input);
isDigit = true;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid digit value, please input again!");
}
}
return value;
}
}