javaisjusttoohard
javaisjusttoohard

Reputation: 39

Java - Basic use of arrays

This is a basic question but I do need some help.

Given two arrays of ints, a and b, return true if they have the same first element or they have the same last element. Both arrays will be length 1 or more.

commonEnd({1, 2, 3}, {7, 3}) → true

commonEnd({1, 2, 3}, {7, 3, 2}) → false

commonEnd({1, 2, 3}, {1, 3}) → true

I have the following code but it wont compile:

public boolean commonEnd(int[] a, int[] b) {
    if(a[0] == b[0] || a[a.length-1] ==b[b.length-1])
        return true;
}

Upvotes: 1

Views: 1233

Answers (5)

ritesh_ratn
ritesh_ratn

Reputation: 157

This code works fine:-

public boolean commonEnd(int[] a, int[] b) {
  int length1=a.length;
  int length2=b.length;
  if(a[0]==b[0]||a[length1-1]==b[length2-1]){
    return true;
  }
  return false;
}

Upvotes: 0

Rakhita Wickramatunge
Rakhita Wickramatunge

Reputation: 4503

public boolean commonEnd(int[] a, int[] b) {
  if((a[0] == b[0]) || (a[a.length-1] ==b[b.length-1]))
      return true;
  return false;
}

You have missed the return statement(if the if statement no true), that's why it didn't compile.

Upvotes: 0

thar45
thar45

Reputation: 3560

Expects return Statements for the function

public boolean commonEnd(int[] a, int[] b) {
    if(a[0] == b[0] || a[a.length-1] ==b[b.length-1]) //Missed `)`
          {
          return true;
          }
        return false;
     }

Upvotes: -1

Sean F
Sean F

Reputation: 2390

you had no return type if, if is untrue

  public boolean commonEnd(int[] a, int[] b) {
  if(a[0] == b[0] || a[a.length-1] ==b[b.length-1])
      return true;
  return false;
  }

Upvotes: 0

Thilo
Thilo

Reputation: 262504

  • You have missing right paren for the if.

  • You need to return something (false) in the "else" part.

You should have gotten a compiler error to tell you this.

Personally, I'd get rid of the if altogether and do

return  a[0] == b[0] || a[a.length-1] ==b[b.length-1];

(but this may be considered hard to read)

Upvotes: 4

Related Questions