else if (b[x != null]){
不是一个有效的语句,这将导致错误,因为(x != null) = true 所以与else if (b[true]){ 相同,没有多大意义。
此外,int 的空array 位置永远不会是null,而是零0。
改用这个:
else if (b[x] != 0){
还有一件事:正如标题所说,使用List 代替array 来拥有可变数量的元素:
public int[] make2(int[] a, int[] b) {
List<Integer> answers = new ArrayList<Integer>();
for(int x = 0; x <= 1; x++){
if(a[x] != 0) {
answers.add(a[x]);
} else if (b[x] != 0) {
answers.add(b[x]);
}
}
}
注意事项:
- 使用
answers 而不是answer,是具有多个元素的List 的更好名称。
- 照常使用 ALWAYS
{ 即使里面的语句只有一行
- 您的函数无效,因为不包括
return answer
编辑
对不起标题,我的错误。是数组
在这种情况下,请记住数组不可调整大小,因此在创建数组时检查最大大小:
int maxSize = a.length > b.length ? a.length : b.length;
int[] answer = new int[maxSize];
注意:您可以在循环中使用此变量来检查最大数量...
编辑2
空数组位置用 0 表示?例子 make2({}, {1, 2}) → {1, 2} 怎么样,a[0] != 0 会跳过吗?因为索引 0 不存在?
-
你不能使用make2({}, {1, 2}),在这种情况下不是一个有效的声明。要模拟此操作:
public static void main(String[] args) {
int a[] = new int[2];
int b[] = new int[2];
b[0] = 1;
b[1] = 2;
make2(a,b);
// if you want to see the output:
System.out.println(Arrays.toString(make2(a,b)));
}
-
它不会跳过它,它会抛出一个ArrayIndexOutOfBoundsException,在这种情况下,你必须让你的函数失效安全,为此,只需在访问元素之前检查长度以断言它是否存在:
public static int[] make2(int[] a, int[] b) {
int[] answer = new int[2];
for(int x = 0; x <= 1; x++){
if(a.length >= x && a[x] != 0) {
answer[x] = a[x];
} else if (b.length >= x && b[x] != 0){
answer[x] = b[x];
}
// optional
else {
answer[x] = -1; // this tells you there's no valid element!
}
}
return answer;
}
解决方案:
http://www.codingbat.com/prob/p143461这是问题的网址:D
好吧,你错过了这些例子,一切都会更清楚......这段代码通过了所有测试。
public int[] make2(int[] a, int[] b) {
int[] answer = new int[2]; // create the array to fill
int y = 0; // create a variable to check SECOND array position
for(int x = 0; x <= 1; x++){ // make 2 iterations
if(a.length > x) { // if ARRAY a has a possible value at POSITION x
answer[x] = a[x]; // put this value into answer
} else if (b.length > y){ // if ARRAY a does not have possible value at POSITION x,
// check if ARRAY b has some possible value at POSITION y
// (remember y is the variable that keeps position of ARRAY b)
answer[x] = b[y++]; // put b value at answer
}
}
return answer; // return answer
}