2014-03-02 17 views
0

嗨,大家好,我只是好奇如何編寫一個數組的代碼,將排序索引,以匹配以前的數組的輸入。我的意思如何編寫並行數組

例子:

如果陣列1有順序輸入:

1,2,3,4 

如何索引變量會看在陣列1

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

然後我問一個用戶從前面的數組中輸入一個數字,以便他們可以添加信息。

user input = 2 

現在我問他們想要添加到該類別的信息是什麼?

他們輸入:​​

我會希望發生的:

Array 1: 
A[1] = 2 

Array 2: 
A[1] = apples 

說明在編碼:(請無視,如果我忘了什麼事)

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? 
} 
} 

我想創建一些以雙重形式輸入輸入並且能夠按照數組「數字」已經索引其變量的順序排列它們的東西。所以我可以保持數組索引相互對應。

編碼看起來如何讓數組2的索引以正確的順序排序,以便它與數組1的索引相匹配,以便以這種方式對它們進行排序?

對不起,如果這是一個微不足道的問題,我真的找不到辦法。 謝謝。

+0

給我一秒讓我嘗試寫一個代碼 – user3287957

+0

我想他不是問關於Arrays.sort(),而是如何根據提供的值的位置在用戶定義的索引中插入到匹配長度的第二個數組中首先。 – indivisible

+0

我也不確定他的問題。每次改變某個東西時你想要一個新的數組,並保留舊數組? – nha

回答

3

取決於如果我理解正確,你......

這裏是我的建議。製作兩個陣列,A1[]A2[]。他們都將是相同的大小。

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(); 

這將讓數組值,用戶希望在A1(由in存儲)的變化並搜索A1[]值。 A1[]中的值的索引保存在index中,用於在A2[]中查找相同的位置。然後詢問A2[]中的新輸入。

希望這會有所幫助。乾杯。

相關問題