Java 使用try-and-catch块对数组中的10个数字求和

Java 使用try-and-catch块对数组中的10个数字求和,java,Java,我对在数组中求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假设

我对在数组中求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");
}
    }
}

你的代码在哪里?请添加你的代码好吗?如果你得到ArrayIndexOutOfBoundsException,我说你做错了
它使用try,catch块来处理ArrayIndexOutOfBoundsException我将删除该位,因为您不需要它。为什么您需要处理ArrayIndexOutofBond异常?当您知道数组的大小时?为什么需要在此处尝试捕获块,如果您现在正在检查索引?感谢大家发表评论~这是讲师的练习~我第一次看到使用ArrayIndexOutOfBoundsException对数字求和~感谢Ravindra~我理解您的编码~它将数组从0到9求和。@RohitJain可能是因为违反了官方java编码习俗。(虽然不是我)@Alderath根据OP的下一个问题,我怀疑他真的想捕获异常,而不是修复代码,这样它就不会抛出异常。AFAIK它遵循Java编码惯例@PeterLawrey这些约定要求您(以及if-,while-,等等)阻塞。它似乎自1999年以来一直在更新<代码>//避免!这省略了大括号{}IMHO不容易出错。;)我怀疑Alerath只是想想象投票被否决的原因。我怀疑是OP希望编写示例代码,捕获一个基于后续问题(也关于异常)的异常。
for (int i = 0; i <= ia.length; i++)