Java: Finding the shortest word in a string and printing it out

前端 未结 4 453
春和景丽
春和景丽 2020-12-21 11:11

I\'m a novice with Java. I took a class in C, so I\'m trying to get myself out of that mode of thinking. The program I\'m writing has a section in which the user enters an i

4条回答
  •  太阳男子
    2020-12-21 11:25

    You're almost there, but your comparison to detect the shortest word is reversed. It should be:

    if (words[i].length() < shortestword.length()) {
    

    That is, if your current word's length is less than the length of your previous shortest word, overwrite it.

    Also, instead of starting with an empty String, start with the first word, i.e., words[0]. Otherwise, the empty string will always be shorter than any string in your array:

    String[] words = sentence.split(" ");
    String shortestword = words[0];
    for (int i = 1; i < numwords; i++) { // start with 1, because you already have words[0]
    

提交回复
热议问题