else if (b[x != null]){
Is not a valid statement, this will cause an error because (x != null) = true
so is the same as else if (b[true]){
which does not make much sense.
Also, an empty array
position of int
will never be null
but zero 0
instead.
Use this instead:
else if (b[x] != 0){
One more thing: as title says, use List
to instead of array
to have a variable number of elements:
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]);
}
}
}
NOTES:
- use
answers
instead of answer
, is better name for a List
with multiple elements.
- take as usual to use ALWAYS
{
even if the statements inside are just one line
- your function is not valid since does not include
return answer
EDIT
Sorry about the title, my mistake. It is arrays
In this case, just remember arrays are not resizeable, so in the moment of creating the array check maximum size:
int maxSize = a.length > b.length ? a.length : b.length;
int[] answer = new int[maxSize];
NOTE: you can use this variable in your loop to check max number...
EDIT2
An empty array position is represented by a 0? What about the example make2({}, {1, 2}) → {1, 2}, will a[0] != 0 skip it? because index 0 doesn't exist?
you cannot use make2({}, {1, 2})
, not a valid statement in this case. To simulate this do:
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)));
}
It won't skip it, it will throw an ArrayIndexOutOfBoundsException
, in this case, you must make you function failsafe, for this, just check lenghts before accessing the element to assert it will exist:
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;
}
SOLUTION:
http://www.codingbat.com/prob/p143461 Here is a url to the question :D
Ok, you were missing the examples, all would be much clearer... This code pass all tests.
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
}