Matrix 'conditional Logic can be removed' checkstyle - java

public static boolean isCompatibleForMultiplcation(final Matrix a, final Matrix b)
{
if (a == null)
{
throw new IllegalArgumentException("a cannot be null");
}
if (b == null)
{
throw new IllegalArgumentException("b cannot be null");
}
if(!(a.getNumberofColumns()== b.getNumberOfRows()))
{
return false;
}
else
{
return true;
}
}
I am getting a 'Conditional Logic can be removed argument in checkstyle for the following method. I cannot seem to figure out why... Can someone give me a pointer?

It is complaining about this part right here :
if(a.getNumberofColumns() != b.getNumberOfRows())
{
return false;
}
else
{
return true;
}
Whenever you see yourself writing code like this you can easily replace it with a single line by just returning the condition from the if statement:
return a.getNumberofColumns() == b.getNumberOfRows();
This statement will return true if the the number of columns for a and rows for b are equal, and false otherwise.

Related

compareTo() method throwing "This method must return int" error despite returning int in method

I'm working on an assignment for my computer science course requiring me to implement a Comparable interface.
We haven't discussed the interface at any sort of length except just being told it compares two objects and returns less than, greater than and equal to, but literally that's about it, which is frustrating.
I intend to do more research on it, but for now I am finding I'm confused as to why my implementation of the compareTo() method isn't working.
Eclipse is giving me an error that compareTo() must return an int, but if you notice, I am returning an integer value. So what might be the issue?
public int compareTo(Task taskToCompare) {
if(this.complete && taskToCompare.isComplete()) {
if(this.priority == taskToCompare.getPriority()) {
return 0;
}
else if(this.priority < taskToCompare.getPriority()){
return -1;
}
else if(this.priority > taskToCompare.getPriority()) {
return 1;
}
} else if(this.complete == true && taskToCompare.isComplete() == false) {
return -1;
} else if(this.complete == false && taskToCompare.isComplete() == true) {
return 1;
}
}
If the return type is int, you will have to return an int or throw an exception. Just exiting the method without a return will lead to a compiler error.
If you have a if-else-if condition, there may be a case where none of the blocks is called. You therefore should create an else statement with a return.
Also, the result of isComplete() and taskToCompare.getPriority() may change if you call the method multiple times. The compiler doesn't know if your logic prevents that.
For example, this is the case if complete is false and isComplete() also returns false. As before, the compiler doesn't know if your logic prevents that.
I think you want something like:
public int compareTo(Task taskToCompare) {
if(this.complete && taskToCompare.isComplete()) {
if(this.priority == taskToCompare.getPriority()) {
return 0;
}
else if(this.priority < taskToCompare.getPriority()){
return -1;
}
else{
return 1;
}
} else if(this.complete == true && taskToCompare.isComplete() == false) {
return -1;
} else if(this.complete == false && taskToCompare.isComplete() == true) {
return 1;
}else{
return 0;
}
}
What if this.complete == false and taskToCompare.isComplete() == false?
The compiler is complaining because you haven't covered every case.
more compact version:
public int compareTo(Task taskToCompare) {
int completeCompare = (this.complete == taskToCompare.complete) ? 0 : (this.complete ? 1 : -1);
if(completeCompare==0) {
return this.priority-taskToCompare.getPriority();
}
return completeCompare;
}

How do I check if a method returns a true or false?

So I have this code
public static boolean isVowel (char c) {
if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
{
return true;
}
else
{
return false;
}
}
and this code in two seperate methods
if (isVowel == true()) //I know this is wrong but how could I make it work?
{
//run command
}
else
{
//run command
}
how could I make if (isVowel()) test if if isVowel true?
public static boolean isVowel (char c) {
// concise code here
return (c=='a'|| c=='e'|| c=='i'|| c=='o'|| c=='u');
}
// your fix here
if (isVowel(aCharVariable)) {
// your code here
} else {
// your code here
}
Concise and simple.
I don't know if I got the question right but here is what I think meets your requirements:
if (isVowel(/* put a char here */) == true) {
// Do stuff
} else {
// Do other stuff
}
In this case (because isVowel() is of type boolean you can also do this which is more elegant:
if (isVowel(/* put a char here */)) {
// Do stuff...
This is possible because the if statement checks for conditions which is nothing else than a boolean state (true or false).
In Java, an if statement checks whether its operand is true or false. Operands can only be of type boolean (and to a certain extent the boxed Boolean variant).
boolean b = true;
if (b) {
System.out.println("b was true");
}
Instead of assigning the static value/the literal true to the variable, you can also assign the result of a method call:
boolean b = isVowel('a');
if (b) {
System.out.println("a is a vowel");
}
Now, you do not necessarily need the variable, you can inline it and use the result of the method call directly:
if (isVowel('e')) {
System.out.println("e is a vowel too");
}
Note that some operators, such as ==, !=, <, return boolean values as well:
boolean greater = 5 > 3;
boolean equal = null == null;
boolean different = new Object() == new Object();
if (greater) {
System.out.println("5 is greater than 3");
}
if (equal) {
System.out.println("null equals null");
}
if (different) {
System.out.println("Two object instances have different idententity");
}
Of course, you do not need variables here and can put the comparison expression directly into the if:
if (5 > 3) {
System.out.println("5 is greater than 3");
}
if (null == null) {
System.out.println("null equals null");
}
if (new Object() == new Object()) {
System.out.println("Two object instances have different idententity");
}
or even:
if ((5 < 3) == false) {
System.out.println("The (logical) statement '5 is less than 3' is false. Therefore, the result of the boolean comparison is true and this code is executed");
}
Another way to write it that gets rid of all the ors.
private static final Set<Character> VOWELS = ImmutableSet.of('a','e','i','o','u');
public boolean isVowel(char c) {
return VOWELS.contains(c);
}
if(isVowel('a')) {
//do stuff
}

writing a java method that returns a boolean from a search

I have written a method that searches a tree to test if any integers are negative.
But I am struggling to get the right Boolean value returned. Any pointers as to where I am going wrong?
What I want to achieve is that as soon as the condition statement is met a false is returned but unfortunately my code is always returning a true
static boolean allE(Tree<Integer> x) {
if (x.isEmpty()) return true;
else {
if (x.getValue()%2 != 0) return false;
}
allE(x.getLeft());
allE(x.getRight());
return true;
}
When you recurse on allE you need to consider the result of that recursion. Easiest fix I see, change
allE(x.getLeft());
allE(x.getRight());
return true;
to
return allE(x.getLeft()) && allE(x.getRight());
Although, I think it makes more sense to write the algorithm such that you recurse on even explicitly. And allE saves three letters compared to allEven (please use meaningful names for methods and variables). Something like,
static boolean allEven(Tree<Integer> node) {
if (node.isEmpty()) {
return true;
} else if (node.getValue() % 2 == 0) {
return allEven(node.getLeft()) && allEven(node.getRight());
}
return false;
}
You're not using the results of your recursive tests properly.
It should be:
if (x.isEmpty()) {
return true;
}
boolean thisNodeEven = x.getValue() % 2 == 0;
return thisNodeEven && allE(x.getLeft()) && allE(x.getRight());
I suppose you need to evaluate the return-value of the recursive calls:
static boolean allE(Tree<Integer> x)
{
if (x.isEmpty())
return true;
else {
if (x.getValue()%2 != 0) return false;
}
if(!allE(x.getLeft()) || !allE(x.getRight()))
return false;
return true;
}

How to check if a Binary Search Tree is Perfectly Balanced?

I have this homework problem and I have completed all methods except this one, isPerfectlyBalanced().
All my tests pass except one that should return false but instead returns true. I have attached my current code and the test that is failing. Any description on how to go about this or even let me know where my code is wrong is appreciated!
private boolean isPerfectlyBalanced(Node node) {
if (node == null) {
return true;
}
if(size(node.left) == size(node.right)) {
return true;
}
isPerfectlyBalanced(node.left);
isPerfectlyBalanced(node.right);
return false;
}
public boolean isPerfectlyBalancedS() {
// TODO
if (root == null) {
return true;
}
return isPerfectlyBalanced(root);
}
Here is my test that is failing:
assertFalse(set.isPerfectlyBalancedS());
Thank you!
My size method:
private int size(Node node){
if (node == null){
return 0;
} else {
return (size(node.left) + 1 + size(node.right));
}
}
public int size() {
// TODO
return size(root);
}
On the last line of the first method, you probably want to do this:
return (isPerfectlyBalanced(node.left) && isPerfectlyBalanced(node.right));
instead of
isPerfectlyBalanced(node.left);
isPerfectlyBalanced(node.right);
return false;
In your code, you dismiss the result of the isPerfectlyBalanced on the subtrees and always return false.

Recursive Function Missing Return Statement

I'm new to recursion and I don't see why this function won't compile. It is apparently missing a return statement. From testing it also seems as though my return statements do not return?
// recursive search method
public BinaryTree<T> recursiveSearch(BinaryTree<T> t, T key) {
if (key.compareTo(t.getData()) < 0) {
if (t.getLeft() != null) {
recursiveSearch(t.getLeft(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) > 0) {
if (t.getRight() != null) {
recursiveSearch(t.getRight(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) == 0) { // key is found
return t;
} else { // not in binary tree
return null;
}
}
The problem is on the lines inside the if branches that make recursive calls.
Your code will behave correctly when it reaches any of your else branches, because all of them have return null. If code takes one of the if branches, however, the control would reach the end of your method without hitting a return. The fix is simple - add the missing returns:
return recursiveSearch(t.getRight(), key);
Yes, it is missing a return statement for the recursion statements.
public BinaryTree<T> recursiveSearch(BinaryTree<T> t, T key)
{
if (key.compareTo(t.getData())<0){
if (t.getLeft() != null) {
recursiveSearch(t.getLeft(), key); // This case doesn't return anything
} else { return null;}
} else if (key.compareTo(t.getData())>0) {
if (t.getRight() != null) {
recursiveSearch(t.getRight(), key); // This case doesn't return anything
} else {return null;}
} else if (key.compareTo(t.getData())==0){ // key is found
return t;
} else {
//not in binary tree
return null;
}
}
I dont know your program logic, but if I have to guess, you might wanna add a return statement to the recursive calls. Like so,
return recursiveSearch(t.getLeft(), key);
and
return recursiveSearch(t.getRight(), key);

Categories