[英]Create multiple arrays using a for loop
I would like to make a program where the user can input the number of variables and fill every variable with certain values. 我想制作一个程序,用户可以在其中输入变量数量,并用特定值填充每个变量。 For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
例如,用户输入要创建10个数组,然后用户输入第一个数组应包含5个元素,然后用户用值填充该数组,然后用户希望第二个数组包含4个元素并执行一样等等。
This is the code I was using, but it doesn't work: 这是我使用的代码,但是不起作用:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs? 以及如何比较用户输入的这些数组?
The problem is that each time you are creating the array. 问题在于,每次创建阵列时。 try this:
尝试这个:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. 您无需创建一维数组,而是创建锯齿状数组。 Essentially, a 2d array is an array of arrays.
本质上,二维数组是数组的数组。 that way the user inputs the number of arrays (
i
) and then continues to fill the arrays. 这样,用户输入数组的数量(
i
),然后继续填充数组。
To check whether two collections have no commons values, you can use 要检查两个集合是否没有公共值,可以使用
Collections.disjoint();
This should work (with bidimensionnal array) 这应该工作(与双向阵列)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++") 您还必须在第二个循环中替换增量(“ q ++”而不是“ p ++”)
This should work and solve their first point 这应该工作并解决他们的第一点
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.