1

Given 2 int arrays, a and b, return a new array length 2 containing, as much as will fit, the elements from a followed by the elements from b. The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays.

I'm wondering how to use a !=, and null. This is the first question I've used it in and I'm having a few errors. So my logic was to iterate through list a, until a null point, then go onto list b.

public int[] make2(int[] a, int[] b) {
      int[] answer = new int[2];
      for(int x = 0; x <= 1; x++){
          if(a[x] != null)
              answer[x] = a[x];
          else if (b[x != null]){
              answer[x] = b[x];
          }
      }

}

Something like this. Any tips on how to check for emptiness?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
NewtoJava
  • 49
  • 6

3 Answers3

1
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?

  1. 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)));
    }
    
  2. 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
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Sorry about the title, my mistake. It is arrays. – NewtoJava Dec 16 '15 at 11:25
  • actually using list or not to store `answers` is not important, use arrays but check my edit and tell me if it works for you ;) – Jordi Castilla Dec 16 '15 at 11:26
  • 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? – NewtoJava Dec 16 '15 at 11:34
  • nope, this is not an empty position, is an empty array with no positions at all wil throw `ArrayIndexOutOfBoundsException` – Jordi Castilla Dec 16 '15 at 11:36
  • also, you cannot call `make2({}, {1, 2})` is not a valid expression in this case – Jordi Castilla Dec 16 '15 at 11:38
  • @NewtoJava please check EDIT2, and don't hesitate to ask further explanations if necessary – Jordi Castilla Dec 16 '15 at 11:48
  • If you're interested, I still couldn't get it working so I made spaghetti code and the answer is; public int[] make2(int[] a, int[] b) { int[] answer = new int[2]; if(a.length == 0) return b; else if(b.length == 0){ answer[0] = a[0]; answer[1] = a[1]; } else if (a.length == 1){ answer[0] = a[0]; answer[1] = b[0]; } else if (a.length >= 2){ answer[0] = a[0]; answer[1] = a[1]; } return answer; } – NewtoJava Dec 16 '15 at 12:22
  • actually the code is not correct, you can return a in the second case, but, what errors you get with the code in `EDIT2`??? – Jordi Castilla Dec 16 '15 at 12:23
  • check the solution in my answer ;) – Jordi Castilla Dec 16 '15 at 12:40
  • I havent used y++ without being in a for loop like x++ on line 4, does it use the value of 0 in the indexing and then increase it to 1?, your code if something I wouldn't have thought of at my earn learning of java. Well written. Thanks for the help. – NewtoJava Dec 16 '15 at 13:05
  • `answer[x] = b[y++];` uses actual `y` value **AND** after, increases `y` in `1`. Take a look to [**this question for clarification**](http://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java), is equivalent to this 2 lines: `answer[x] = b[y]; y = y + 1;` – Jordi Castilla Dec 16 '15 at 13:08
  • Could you possibly explain your pathway of thinking to create this code? When you saw the question what were your precautions to prevent over indexing. – NewtoJava Dec 16 '15 at 13:17
  • 1
    Oh I see, you were abusing the idea that the length is always higher than the indexs. So you were comparing length and index, so to find an available index. The length must be higher than the index, and you were using that idea to check if the index was available. – NewtoJava Dec 16 '15 at 13:31
  • exactly, but keep in mind you need 2 indexes: `x` index that is used for array `a` and array `answer` **AND** `y` index, that will be used **ONLY IF NECESSARY** to check array `b`. Check also new comments in the **SOLUTION**, hope they clarify – Jordi Castilla Dec 16 '15 at 14:27
  • Hi @NewtoJava as this is your first question, you must know if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. Of course, there is no obligation to do this. – Jordi Castilla Dec 17 '15 at 10:53
0

You can check array if it string but your array is int. so you can use the following example

int arr[] = null;
if (arr != null) {
  System.out.println("array is null");
}


arr = new int[0];
if (arr.length != 0) {
  System.out.println("array is empty");
}
Vicky
  • 1,412
  • 4
  • 18
  • 30
-1

I have a few questions, before I suggest you some alternatives. 1. why are you declaring int[] answer = new int[2]; when question says 2 or more elements.

You should use :

List<int> stockList = new ArrayList<int>();

if(a[x] != null)
    stockList.add(a[x]);
else if (b[x] != null){
    stockList.add(b[x]);
}

int[] stockArr = new int[stockList.size()];
stockArr = stockList.toArray(stockArr);
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57