简体   繁体   中英

How to find longest word in string WITHOUT arrays or methods that parse words for you

This is for a homework assignment that I have been stuck for a while now. The task is to use a loop to determine what the longest word is. In my head, the logic seems to be working fine, but somehow the output always sticks to the penultimate length of the word in the string. For example, if I enter 'tom cook' as textBoi, the output comes back as 3, although the desired output should be coming out as 4. TIA!!

public static void longboi(String textBoi)
{
    int lengthCounter = 0;
    int final = 0;
    int textLength = textBoi.length();

    for (int i = 0; i < textLength; i++)
    {
        String indexValue = Character.toString(textBoi.charAt(i));

        if(" ".equals(indexValue) || indexValue.equals(textBoi.charAt(textBoi.length()-1))) //if current index == space or last value of textBoi do this
        {
            if (lengthCounter > final) //if the lengthCounter is greater than the value you have right now, do this
            {
                final = lengthCounter;
                lengthCounter = 0;
            }
            else //if not, reset counter
            {
                lengthCounter = 0;
            }
        }
        else //otherwise, keep on counting
        {
            lengthCounter = lengthCounter + 1;
            System.out.print(lengthCounter);

        }            
    }
    System.out.println("this is output: " + final); //print out answer

}

You are getting that wrong result because if this condition

indexValue.equals(textBoi.charAt(textBoi.length()-1))

when you reached last character in the string you need to increment current count if it is not " " and only after that compare with current maximum length.

Also please read about debuggers and how to use them in Java. Once you learn it you will be able to easily solve such questions yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM