我对程序查找数组中 10 个数字的总和有问题。 它使用 try, catch 块来处理 ArrayIndexOutOfBoundsException。请帮帮我...
我会尝试类似的东西
int[] nums = new int[10];
// give it some values.
long sum = 0;
for(int n: nums) sum += n;
System.out.println("Sum is " + sum);
你不需要捕获 ArrayIndexOutOfBoundsException
假设你的代码的正确程序是
class ravindra {
public static void main(String[] args) {
int[] ia = new int[10];
try{
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
catch(ArrayIndexOutOfBoundsException e)
{
//system.out.println("exception");
}
}
}
对于异常的发生,您的代码通过for loop
循环,直到数组绑定超出界限(即数组长度+1)
for (int i = 0; i <= ia.length; i++)