开发者

Why doesn't setting variables equal to an array index work in the expected way?

Two versions of very similar code... one works, the other doesn't...

Array Used:

int[] input = new int[10];  

//

f开发者_运维知识库or(int i = 0; i < input.length; i++) {
                //int inputi = input[i];
            for(int j = 0; j < input.length; j++) {
                //int inputj = input[j];
                if(input[i] < input[j]) {
                      input[j] = input[i];
                      min = input[j];
                  }
            }

The code above works. The code below doesn't, what gives?

for(int i = 0; i < input.length; i++) {
                int inputi = input[i];
            for(int j = 0; j < input.length; j++) {
                int inputj = input[j];
                if(inputi < inputj) {
                      inputj = inputi;
                      min = inputj;
                  }
            }

Shouldn't it do the exact same thing? The first code returns the minimum value, the second does not.

Sorry for the possibly confusing variable names, I only chose those so I could easily switch back and forth.


the assignment is broken: inputj and inputi are temporary variables.

                  inputj = inputi;

changes temporary variable

                  input[j] = input[i];

actually changes the array values.

just to get the min value:

min = input[0];
for(int i = 1; i < input.length; i++) {
            if(min > input[i]) {
                  min = input[i];
            }
}


Are you just trying to get the minimum value of the array?

int min = input[0];
for (int i = 0; i < input.length; i++) {
  if (input[i] < min) {
    min = input[i];
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜