Reputation: 31
I'm new to java and as such, I'm not entirely sure if I did this right. What I'm trying to do is find out if the number of items in a list of Strings is even and a primitive.
public class LearnAboutInputs {
public boolean isEven(String[] value) {
if (value.size() % 2 == 0 && boolean == true) {
return true;
} else {
return false;
}
}
}
Upvotes: 0
Views: 1686
Reputation: 1685
What you put there is not valid. A minimal edit to make it valid would be:
public class LearnAboutInputs {
public boolean isEven(String[] value) {
if(value.length % 2 == 0) {
return true;
}
else {
return false;
}
This assumes you intended to look at the length of the array, as opposed to looking at the size() of a string or strings within.
However, the if check is in itself boolean, so you could more succinctly write:
public class LearnAboutInputs {
public boolean isEven(String[] value) {
return value.length % 2 == 0;
}
SeeDart and PoisonedYouth bring up a good point about null checking, so adding that to the succinct example results in:
public class LearnAboutInputs {
public boolean isEven(String[] value) {
return value != null && value.length % 2 == 0;
}
If the value is null, the statement short-circuits to false, so the second half won't be evaluated, making this valid.
If you want to return an object of class Boolean
rather than a primitive boolean
, change the return type from lowercase ‘boolean’ to the initial-cap ‘Boolean’ word. The handy autoboxing features will do the legwork for you.
public class LearnAboutInputs {
public Boolean isEven(String[] value) { // Return object rather than primitive.
return value != null && value.length % 2 == 0; // Autoboxing transforms the generated `boolean` primitive value into a `Boolean` object.
}
Upvotes: 5
Reputation: 140525
There are various things here. Lets rewrite:
public class LearnAboutInputs {
public boolean hasEvenLength(String[] value) {
if (value != null && value.length % 2 == 0) {
return true;
}
return false;
}
}
Reasonable changes here:
Upvotes: 0
Reputation: 7798
Your code is almost correct. There were a few syntax errors I fixed but I'm not sure what you were trying to do with boolean == true
. It's also good practice to make sure your input is valid!
public class LearnAboutInputs {
public boolean isEven(String[] value) {
if (value == null) {
return false;
}
if (value.length % 2 == 0) {
return true;
}
else {
return false;
}
}
}
Upvotes: 3