how to write a parallel array [duplicate]

2019-09-16 19:04发布

问题:

This question already has an answer here:

  • Sort a parallel array using Arrays.sort() 5 answers

hi everyone I'm just curious on how one would write a code for an array that will sort indexes in order to match a previous array's inputs.

Example of what i mean:

If array 1 had inputs in this order:

1,2,3,4

How the indexed variables would look in array 1

A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4

Then i ask a user to input a number from the previous array so they can add information to.

user input = 2

Now i ask what information do they want to add to that category?

They input : apples

What i would want to happen:

Array 1:
A[1] = 2

Array 2:
A[1] = apples

Explanation in coding: (please disregard if i forgot something)

 import java.util.Arrays
 import java.util.Scanner;
 public static parallelArrays {
   public static void main (String[] args) {
     Scanner input = new Scanner (System.in);

//arrays and declarations
int [] numbers = new int [4];
double [] money = new double [4];

  system.out.println("Please enter 4 digits");                 
     for (int i = 0 ; i < numbers.length; i++) {
       numbers[i] = input.nextInt();  
      }

  system.out.println("please choose the number you would want to add more information   
     to");

      for (int i : numbers)
        {
          System.out.println(i + "; ");
        }
     //this is where I'm lost
     //how should i write the code to get user input that will align with array "numbers" 
     // index?
 }
}

i would like to create something that takes in inputs in double form and is able to align them in the order that array "numbers" has indexed its variables. so that i may keep the array indexes corresponding to each other.

how would the coding look to get the index of array 2 to sort itself in the correct order so that it will match the index of array 1 in order to keep them sorted in this way?

Sorry if this is a trivial question, i really can't find a way to do so. thank you.

回答1:

Depending on if I am understanding you correctly...

Here is what I would recommend. Make two arrays, A1[] and A2[]. They will both be the same size.

System.out.println("please choose the number you would want to add more information to");
int in = input.nextInt();

int index;
for (int i = 0; i < A1.length; i++){
    if (A1[i] == in)
        index = i;
}

System.out.println("Enter the new entry:");
A2[index] = input.next();

This will get the array value that the user want the change in A1 (stored by in) and search for the value in A1[]. The index of the value in A1[] is saved in index and used to find the same position in A2[]. the new input in A2[] is then asked for.

Hope this helps. Cheers.