Multiplying all values of an array using an enhanc

2020-04-01 08:50发布

问题:

The title pretty much covers it. For some reason this problem is escaping me and I can't find the logical answer to this.

EDIT:

Say I have

int[] values = (2,5,3,2,1,4,6,3,2,1,5,3)

I want to get the product of multiplying all these elements. My textbook asks to do this with an enhanced for loop.

for (int element : values)
{
NO CLUE WHAT TO PUT HERE
}

My first guess, however, was that it couldn't be done with an enhanced for loop.

Is my textbook just trying to trick me to teach me some sort of lesson?

回答1:

This can't be done with enhanced for loop. Assume you have an array: (I updated the answer after the OP has updated the question, the update is below).

int[] a = {1,2,3};

When you do:

for(int num : a) {
  num = num*something;
} 

You are actually multiplying another variable (the array won't be affected)..

num in the above example is only a copy of an array element. So actually you are modifying a local variable, not the array itself.

Read this and you'll see that the value in the array is copied into a local variable, and this local variable is used. So this multiplication will not affect the original values of the arrays.


OP UPDATE:

If you want to multiply elements and get the result, you can. Your text book is not trying to trick you. It doesn't ask you to change the values. But to use them in order to do some calculations:

int[] values = {2,5,3,2,1,4,6,3,2,1,5,3};
int result=1;
for(int value : values) {
    result *= value;
} 
System.out.println("The result: " + result); //Will print the result of 2*5*3*2*...


回答2:

This can easily be done with an enhanced for loop:

int result = 1;
for (int element : values)
{
    result *= element;
}


回答3:

It can't be done, you will have to use old-style array addressing:

for (int i = 0; i < array.length; i++) {
  array[i] = array[i] * 2;
}


回答4:

int index = 0;
for (int element : values)
{

    values[index] = element + someVariable;
    index++;
}


标签: java arrays