0

I have a method which takes an array of integers as an input and outputs a string saying which type of triangle they form if the argument is of length 3 and outputting "invalid" otherwise.

    public class Triangle {
        public String typeOf(int[] args) {
            if (args.length < 3) return "invalid"; // invalid
            if (args[0] == args[1] && args[1] == args[2]) return "equilateral";
            if (args[0] == args[1] && args[0] != args[2]) return "isosceles";
            if  (args[0] == args[2] && args[0] != args[1]) return "isosceles";
            if  (args[1] == args[2] && args[0] != args[1]) return "isosceles";
            if (args[0] != args[1] && args[0] != args[2] && args[1] != args[2]) return "scalene";
            return "Error all the tests failed";
        }        
    }

The problem is that the final return statement "return "Error all the tests failed";" can't be reached as the previous if statements cover all possible inputs. This leads to Eclemma showing missing instructions but I can't take it out as I get an error saying it must return a result of type string. Is there a way to make Eclemma ignore this specific statement or a way to cover it in my tests? Tahnks

2 Answers2

0

Change your algorithm to have a single return statement, at the end. Then have each of the if-conditions set their result into the String that will get returned. If you are concerned about short-circuiting later checks once you know the answer, turn them into else if

For example:

public String typeOf(int[] args) {
  String result = "Error all the tests failed";
  if (args.length < 3) result = "invalid"; // invalid
  else if (args[0] == args[1] && args[1] == args[2]) result = "equilateral";
  // ..skipping a few..
  else result = "scalene";
  return result;
}  
sjgp
  • 310
  • 5
  • 17
0

You have all possible cases matching in the if condition and it never reach the final return statement.

Instead of having multiple return statement, you can do below

public String typeOf(int[] args) {
    String str = "isosceles";
    if (args.length < 3)
        str = "invalid"; // invalid
    else if (args[0] == args[1] && args[1] == args[2])
        str = "equilateral";
    else if (args[0] != args[1] && args[0] != args[2] && args[1] != args[2])
        str = "scalene";
    return str;
} 
Saravana
  • 12,647
  • 2
  • 39
  • 57