我有一个名为 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/