java - 如果我的实例是一个数组,我如何设置它的数组类型变量的值

标签 java arrays

我有一个名为 Combination 的类,它有一个数组类型变量。我想做的是将 x (预定义)数量的对象放入数组中。让我困惑的是我的实例和它的变量都是数组。我是否需要一维数组来在其中放置对象,或者由于我的变量是数组,所以它必须是二维的吗?

public class Combination {
    public int[] combination = new int[6];

    public Combination(int[] combination) {
        super();
        this.combination = combination;
    }

    public Combination() {
        super();
    }
}

public class Glavna {
    static Scanner s = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Enter number of combinations");
        int combNum = s.nextInt();
        Combination k = new Combination();
        Combination[] array1 = new Combination[combNum];  // which one of these 2 is correct
        Combination[][] array2 = new Combination[combNum][6];  // which one of these 2 is correct
        k.kombinacija[3] = 5;         // This works fine
        array1[0].combination = 1;      //  This throws NullPointerException
        array2[0][0].combination[0] = 1;    //  This throws NullPointerException
    }
}

输入:2
1 2 3 4 5 6 7 8 9 10 11 12
所需输出:
1 2 3 4 5 6
7 8 9 10 11 12

如果输出被称为final[],那么final[1]是第一行,final[2]是第二行。

谢谢。

最佳答案

请检查此答案是否对您有帮助:

public class Glavna {
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {

    System.out.println("Enter number of combinations");
    int combNum = s.nextInt();
    Combination k = new Combination();
    Combination combination1 = new Combination();  // Combination object 1
    Combination combination2 = new Combination();  // Combination object 2
    System.out.println("Enter inputs");
    for (int i = 0; i < combNum; i++) {
        if (i <= 5) {
            combination1.combination[i] = s.nextInt(); // Assign input set 1 to combination object 1 array
        } else {
            combination2.combination[i-6] = s.nextInt(); // Assign input set 2 to combination object 2 array
        }
    }

    //Print output separately
    System.out.println("Desired output: ");
    for (int l : combination1.combination) {
        System.out.print(l + " ");
    }
    System.out.println();
    for (int l : combination2.combination) {
        System.out.print(l + " ");
    }
}
}

关于java - 如果我的实例是一个数组,我如何设置它的数组类型变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60022822/

相关文章:

arrays - (Swift)当条件为真时删除数组中所有元素的最简单方法是什么

javascript - 使用键从 json 数组中获取 json 对象

c++ - int(*a)的解释[3]

java - 无法解析方法的SparkSession(),我使用的依赖版本是2.4.3

java - 访问名为 variablename+number 的变量

java - Java中的多级SSH登录

c - 如何静态且高效地实现两个节点数组?

java - Neo4j Spring Data 示例缺少注释 @Indexed

java - 输入清理以不破坏 JSON 语法

javascript - 将嵌套数组合并为一个?