Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

java - How to change the value of array elements

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}

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

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,

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...