我想为数组的第一个元素划分我的数组的元素,该方法工作正常,但最后一个元素没有被划分。
我想我必须使用 <= array.length...,但它显然给了我一个数组越界异常。如果没有 <=length,我怎么能做到这一点。 PS:第一个元素不应该被忽略/考虑,因为它是股息。我的代码如下:
public class Ris
{
public static void main()
{
double[] testResult = {2.0, 3.6, 5.0, 2.0};
for(int element = 0; element < testResult.length; element++){
if( testResult[element] > testResult[0]){//excludes 1st element
testResult[element] = testResult[element] / testResult[0] ;// divides elements by first element 0
}
System.out.println(testResult[element]);
}
}
}
最佳答案
你以一种糟糕的方式跳过了第一个元素 -
if( testResult[element] > testResult[0]){
跳过不超过第一个元素的所有内容 - 超过 2.0
你可能想测试一下
if( element > 0){
但是你也可以跳过for循环定义中的第一个元素
for(int element = 1; element < testResult.length; element++){
关于java 将一个数组除以它的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103226/