InExperience
InExperience

Reputation: 103

Is it necessary to have a return in a method to use Junit TDD?

I have this problem: I need to print the duplicated characters in a String. Now if you look my code, without return at the end of the loop I will get the algorithm correct. But if I put the char as return the second loop go out before the end.

It's necessary to get a return at the program to be tested?

This is the code:

        int[] letters = new int[26];
        for (int i = 0; i < s.length(); i++) {
            letters[s.charAt(i) - 97]++;
        }
        for (int i = 0; i < letters.length; i++) {
            if (letters[i] > 1) {
                char c = (char) (i + 97);
                System.out.println(c);
                //return c;
            }
        }

Upvotes: 0

Views: 53

Answers (1)

Max Pringle
Max Pringle

Reputation: 639

Based on the code and comments that have been left, here is my suggestion.

int[] letters = new int[26];
for (int i = 0; i < s.length(); i++) {
    letters[s.charAt(i) - 97]++;
}
char[] copyLoop = new char[26];

for (int i = 0; i < letters.length; i++) {
    if (letters[i] > 1) {
        char c = (char) (i + 97);
        copyLoop[i] = c;            
    }
}
return copyLoop;

Your comment addressed to myself showed the following...

for (int i = 0; i < letters.length; i++) 
{ 
    if (letters[i] > 1) 
    { 
        char c = (char) (i + 97); 
        char[] copyLoop = new char[26]; 
        copyLoop[c]++;
    }
}

The problem with this is that you are declaring a new char array everytime you go into the loop. Declare it outside the loop and add the values to the array. Then return the array.

Based on the comments below to this answer, here is the unit test.

@Test public void test1()
{
    char [] result = c.checkDouble("casa"); 
    Assert.assertEquals("a", String.valueOf(result[0]));
}

Again I can't stress enough my previous comment

That one is on you. Set a break point and debug the test. See the value of result and do a manual compare of "al" vs result. Remember, "al" is a string and you are returning an array of chars.

There are a couple things to keep in mind...

  1. Set a break point in the test method. Step through the method and stop when it gets to the Assert line. Hover over or set a watch to find out the value of result. You can solve this problem easily by doing that.
  2. You will find that when you do that result is an array and you are trying to compare it with a char. Now you have a result of chars in an array but you will need to access a certain one using an index to your array.

Upvotes: 2

Related Questions