Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/java/org/fundacionjala/coding/jose/Middle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.fundacionjala.coding.jose;

/**
* Created by JoseTorrez on 9/4/2017.
* You are going to be given a word. Your job is to return the middle character of the word. If the word's length
* is odd, return the middle character. If the word's length is even, return the middle 2 characters.
*/
public class Middle {

/**
* This method get the middle of a word.
*
* @param word String received.
* @return subWord String.
*/
public String getMiddle(String word) {
String subWord = "";
int length = word.length();
int half = length / 2;
if (length % 2 == 0) {
subWord = word.substring(half - 1, half + 1);
} else {
subWord = word.substring(half, half + 1);
}
return subWord;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may be refactored like this.

        int half = word.length() / 2;
        return word.length() % 2 == 0 ? word.substring(half - 1, half + 1) : word.substring(half, half + 1);

}
}
60 changes: 60 additions & 0 deletions src/test/java/org/fundacionjala/coding/jose/MiddleTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.fundacionjala.coding.jose;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
* Created by JoseTorrez on 9/4/2017.
*/
public class MiddleTest {

private Middle middle;

/**
* Initializer.
*/
@Before
public void setUp() {
middle = new Middle();

}

/**
* Test for even number of characters.
*/
@Test
public void evenTests() {
assertEquals("es", middle.getMiddle("test"));
assertEquals("dd", middle.getMiddle("middle"));
}

/**
* Test for odd numbers of characters.
*/
@Test
public void oddTests() {
assertEquals("t", middle.getMiddle("testing"));
assertEquals("A", middle.getMiddle("A"));
}

/**
* Test for a long even number of characters.
*/
@Test
public void longEvenTest() {
assertEquals("e", middle.getMiddle("thisisalongsequenceofword"));
assertEquals("e", middle.getMiddle("anotherwordforthistestofmiddlecharacter"));
}

/**
* Test for a long odd number of characters.
*/
@Test
public void longOddTest() {
assertEquals("eq", middle.getMiddle("thisisalongsequenceofwords"));
assertEquals("es", middle.getMiddle("anotherwordforthistestofmiddlecharacters"));
}

}