NewtoJava - 1 year ago 81

Java Question

The question I am trying to solve is: http://codingbat.com/prob/p128270

Given 2 int arrays, a and b, of any length, return a new array with the first element of each array. If either array is length 0, ignore that array.

`front11({1, 2, 3}, {7, 9, 8}) → {1, 7}`

front11({1}, {2}) → {1, 2}

front11({1, 7}, {}) → {1}

My Code so far:

`public int[] front11(int[] a, int[] b) {`

int answerindexs = 2;

if(a.length == 0 || b.length == 0)

answerindexs = 1;

if(a.length == 0 && b.length == 0)

answerindexs = 0;

int[] answer = new int[answerindexs];

for (int x = 0; x <= 1; x++){

if(a.length > 0 && x == 0)

answer[0] = a[0];

else if(b.length > 0 && x == 1)

answer[1] = b[0];

}

return answer;

}

This question I have been trying to do by myself is fully stressing me out because every attempt I try to do java doesn't work the way I thought it did.

The only test I did not pass is;

`front11({}, {2, 8}) → {2}`

Because I get an index out of bound error, and I am having trouble trying to solve for this specific test. As I am not sure how to check if my answer array has an element already in it as answer.length is always 2 eventhough it has no assigned element in each index as it is defaulted to zero.

Any help appreciated, also if anyone could improve my two if statements at the beginning (It works for little numbers but I know when it gets to larger numbers I can't write code like this). I wanted to answer this question using ArrayList as I can just .add(), but this question specifies an array which is annoying to find out how many slots to preset.

Answer

Instead of hardcoding the indexes, use a variable and increment it if the array is not empty.

```
public int[] front11(int[] a, int[] b) {
int answerindexs = 0;
answerindexs = a.length > 0 ? answerindexs + 1 : answerindexs;
answerindexs = b.length > 0 ? answerindexs + 1 : answerindexs;
int[] answer = new int[answerindexs];
//Index variable
int i = 0;
for (int x = 0; x <= 1; x++){
if(a.length > 0 && x == 0)
answer[i++] = a[0];
else if(b.length > 0 && x == 1)
answer[i] = b[0];
}
return answer;
}
```

Source (Stackoverflow)