大家好我只是好奇如何为一个数组编写代码,该数组将对索引进行排序以匹配先前数组的输入。
我的意思是:
如果数组1按此顺序输入:
1,2,3,4
索引变量在数组1中的外观
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
然后我要求用户输入前一个数组中的数字,以便他们可以添加信息。
user input = 2
现在我问他们想要将哪些信息添加到该类别?
他们输入:apples
我想要发生什么:
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 :(得分: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[]
中的新输入。
希望这会有所帮助。欢呼声。