使用for循环创建多个数组 [英] Create multiple arrays using a for loop

查看:196
本文介绍了使用for循环创建多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个程序,用户可以输入变量的数量,并用一定的数值​​填充每个变量。例如,用户输入他/她想要创建10个数组,然后用户输入第一个数组应该有5个元素,用户用数值填充该数组,然后用户想要第二个数组有4个元素,相同的等等。



这是我正在使用的代码,但它不起作用:

  public static void main(String [] args){
Scanner s = new Scanner(System.in);
System.out.println(输入变量的数量:);
int i = s.nextInt();

(int j = 0; j int [] var = new int [j];
System.out.println(输入值的数量:);
int p = s.nextInt();
for(int q = 0; q int n = s.nextInt();
var [q] = n;





$ b

我怎么能比较这些用户输入的数组?

解决方案

问题是每次创建数组时。
试试这个:

 扫描仪s =新扫描仪(System.in); 
System.out.println(输入变量的数量:);
int i = s.nextInt();
int [] [] var = new int [i] [];
for(int j = 0; j
System.out.println(输入值的数量:);
int p = s.nextInt();
var [j] = new int [p];
for(int q = 0; q int n = s.nextInt();
var [j] [q] = n;




$ b不是创建一维数组,而是创建一个锯齿状的阵列。本质上,二维数组是数组的数组。这样用户输入数组的数量( i )然后继续填充数组。



检查是否两个集合没有公共值,您可以使用

  Collections.disjoint(); 

对于其他操作,您可以查看这里


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.

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.

To check whether two collections have no commons values, you can use

Collections.disjoint();

For other operations, you can look here

这篇关于使用for循环创建多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆