开发者

java dividing an array by its elements

开发者 https://www.devze.com 2023-03-07 17:49 出处:网络
I want to divide the elements of my array for the first element of the array, the method is working ok, but the last element is not been divided.

I want to divide the elements of my array for the first element of the array, the method is working ok, but the last element is not been divided.

I think I had to use <= array.length..., but it obviously gives me an array out of bound exception. How can I achieve this without <=length. PS: the first element should not be dived/taken into consideration as it is the dividend. My code is the following:

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 e开发者_StackOverflow中文版lements by first element 0
            }
          System.out.println(testResult[element]); 

        }
    }
}


You're skiping the first elemnt in a bad manner -

if( testResult[element] > testResult[0]){

Skips everything that is not more than first element - more then 2.0

You probably ment to test for

if( element > 0){

But you can also just skip first element in the definition of for cycle

for(int element = 1; element < testResult.length; element++){


if( testResult[element] > testResult[0]){//excludes 1st element

You're testing values, not positions in here. Try this instead:

public class Ris
{
public static void main()
{
    double[] testResult = {2.0, 3.6, 5.0, 2.0};
    for(int element = 1; element < testResult.length; element++){
    testResult[element] = testResult[element] / testResult[0] ;// divides elements by first element 0
      System.out.println(testResult[element]); 

    }
}
}


Instead of:

if( testResult[element] > testResult[0]){//excludes 1st element

You should be using:

if(element > 0){//excludes 1st element

to exclude the 1st element.

Or have your for loop start at 1st position (skip 0th position):

for(int element = 1; element < testResult.length; element++)


To exclude the first element you should start counting from 1, not 0. I.e. change to

for (int element = 1; ....


On a more general note, it's bad practice to but all your variables in one array or to use the same variable for input and output. You should rather have:

double denominator = 2.0;
double[] inputValues = new double[]{3.6, 5.0, 2.0};
double[] outputValues = new double[inputValues.length];

If you do that instead, the for loop now starts at element 0 and ends before (<) inputValues.length, which is usually how for loops are built.

0

精彩评论

暂无评论...
验证码 换一张
取 消