java—如何在没有数组或方法的情况下查找字符串中最长的单词

pcww981p  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(330)

这是一个家庭作业,我已经被困了一段时间了。任务是使用循环来确定最长的单词是什么。在我的脑海中,逻辑似乎运行良好,但不知何故,输出总是坚持字符串中单词的倒数第二个长度。例如,如果我输入'tom cook'作为textboi,输出返回3,尽管所需的输出应该是4。蒂娅!!

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

}
oxf4rvwz

oxf4rvwz1#

你得到了错误的结果,因为如果这个条件

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

当到达字符串中的最后一个字符时,如果当前计数不是“”,则需要递增当前计数,并且仅在此之后与当前最大长度进行比较。
另外,请阅读有关调试器以及如何在java中使用它们的内容。一旦你学会了,你就能自己轻松地解决这些问题。

相关问题