Reputation: 39
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
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
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
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
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
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