0

I have a method that takes in a string.

  • If it has three characters, then I put a : in between the zeroth and first element.
    Example: 1231:23

  • If it has four characters, then I put a : in between the first and and second element.
    Example: 123412:34

For some reason, I keep getting odd results.

Here is my method:

private String addColon(String openOrclose)
{
    String newHour = null;
    if(openOrclose.length() == 3)
    {
        newHour = openOrclose.substring(0,0) + ":" + openOrclose.substring(1,2);

    }
    else
    {
        newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(2,3);
    }
    return newHour;
}

For three characters, my result is :2, and for four characters, my result is 1:3.

Gabe
  • 29
  • 4
TheQ
  • 1,949
  • 10
  • 38
  • 63

3 Answers3

4

You are close. You need to adjust the indicies for the substring calls:

private String addColon(String openOrclose)
{
    String newHour = null;
    if(openOrclose.length() == 3)
    {
        newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(1,3);

    }
    else
    {
        newHour = openOrclose.substring(0,2) + ":" + openOrclose.substring(2,4);
    }
    return newHour;
}
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
0

Your issue seems very much related to this question Insert a character in a string at a certain position

Note: I would have just commented this under your question but I have 49 reputation and need 1 more point to do so.

Community
  • 1
  • 1
JaysonP
  • 164
  • 1
  • 10
0

The issue is the indexes that you're passing into substring():

private String addColon(String openOrclose)
    {
        String newHour = null;
        if(openOrclose.length() == 3)
        {
            newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(1,openOrclose.length());

        }
        else if(openOrclose.length() == 4)
        {
            newHour = openOrclose.substring(0,2) + ":" + openOrclose.substring(2,openOrclose.length());
        }
        return newHour;
    }

Quoted from the Java Doc:

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Examples:

"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"

Gulllie
  • 523
  • 6
  • 21