Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

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

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 integer, n, and then n number of words afterwards. This section then searches through those words and finds the shortest one, then returns it to the user. For instance, an input might be:

INPUT: 4 JAVA PROGRAMMING IS FUN

OUTPUT: IS

The code I have currently seems to return the wrong word. In this instance, it returns "PROGRAMMING", when it should return "IS". I thought maybe you all could point me in the right direction.

int numwords = scan.nextInt();
    String sentence = scan.nextLine();
    String shortestword = new String();
    String[] words = sentence.split(" ");
    for (int i = 0; i < numwords; i++){
        if (shortestword.length() < words[i].length()){
            shortestword = words[i];
    
        }
    }
    System.out.printf(shortestword);

To give you an idea of what I was trying to do, I was attempting to enter the words into a string, "sentence," then break that string up into individual words in an array, "words[]," then run a for loop to compare the strings to each other by comparing the lengths to the entries in the array. Thank you for your assistance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...