如何改变数组元素的值 [英] How to change the value of array elements

查看:154
本文介绍了如何改变数组元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int A = 300;
int B = 400;
int C = 1000;
int D = 500;

int []abcd = {A,B,C,D};
Arrays.sort(abcd);   // the sequence of array elements will be {300, 400, 500,1000}

我想,B,C,D根据排序后的数组中的位置来改变变量A的值

I wanted to change the value of the variables A,B,C,D according to their location in the array after sorting.

例如变量A位于索引0,这样的变化为1,而不是300的值,
    变量B位于索引1,因此B的变化到2而不是400的值,
    变量D被定位于索引2,所以D转换到3,而不是500的值,
    变量C位于指数3,所以C变化对4的价值,而不是1000,

e.g variable A is located at index 0, so the value of A change to 1 instead of 300, variable B is located at index 1, so the value of B change to 2 instead of 400, variable D is located at index 2, so the value of D change to 3 instead of 500, variable C is located at index 3, so the value of C change to 4 instead of 1000,

的变量的最终值将是:
A = 1;
B = 2;
C = 4;
D = 3;

The final value of the variable will be: A = 1; B = 2; C = 4; D = 3;

推荐答案

一个幼稚的方式做到这一点是要经过阵列中的每个元素,检查值,当您去:

A naive way to do it would be to go through each element of the array, checking the values as you go:

for (int i = 0; i < abcd.length; i++)
{
    if (abcd[i] == A)
    {
        A = i+1;
    }
}
// Rinse and repeat for B, C, D

如果走这方法中,当然,把它变成接受阵列,要搜索的值,该数组内返回其索引的函数。

If going down this approach, of course, turn it into a function that accepts the array, the value to search for, and returns its index within the array.

这篇关于如何改变数组元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆