用Java编写一个除法计算器,程序要求在出现除数为零和除数、被除数中有一个不是数字的情况时进行相应的处理。当调用存放在数组中的计算结果,数组有可能产生索引越界,对这种情况进行捕捉和处理。
时间: 2024-11-22 10:36:56 浏览: 28
在Java中,你可以创建一个名为`Calculator`的类,包含一个静态方法`divide`,用于执行除法操作,并捕获可能出现的异常。这里是一个简单的实现:
```java
public class Calculator {
public static double divide(String[] numbers, int index) {
try {
// 检查输入是否有效
if (numbers == null || numbers[index].isEmpty()) {
throw new IllegalArgumentException("Invalid input: cannot be empty or null");
}
// 将字符串转换为double类型的数值
double divisor = Double.parseDouble(numbers[index]);
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
// 从数组中获取被除数
double dividend = Double.parseDouble(numbers[(index + 1) % numbers.length]);
return dividend / divisor;
} catch (NumberFormatException e) {
System.out.println("Error: Both numbers must be numeric.");
return -1; // 返回错误值表示非数字输入
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds. Please provide valid indices for the array.");
return -1;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
return -1;
} finally {
// 清理资源或其他必要的操作(如果有的话)
}
}
public static void main(String[] args) {
String[] inputs = {"5", "0", "2"}; // 示例输入数组
try {
double result = divide(inputs, 0); // 调用并处理异常
System.out.println("Result: " + result);
} catch (IllegalArgumentException | ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
```
在这个示例中,`divide`方法会检查输入的有效性和除零情况,同时捕获并处理`NumberFormatException`, `ArrayIndexOutOfBoundsException`, 和 `ArithmeticException`。在`main`方法中,我们展示了如何调用这个函数并妥善处理返回的结果。
阅读全文
相关推荐


















