Java: find the shortest word in a string and print it out

I am new to Java. I took the class in C, so I am trying to break out of this way of thinking. The program I am writing has a section where the user enters an integer, n, and then n is the number of words. This section then searches those words and finds the shortest, and then returns it to the user. For example, the input could be:

INPUT: 4 PROGRAMMING JAVA FUN

OUTPUT: IS

The code I have now seems to return the wrong word. In this case, it returns "PROGRAMMING" when it should return "IS". I thought maybe you could all 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 trying to enter words in the string "sentence" and then split that string into individual words in the array "words []", then run a for loop to compare the strings with each other. comparing the lengths with the entries in the array. Thank you for your help!

+2


source to share


4 answers


You are almost there, but your comparison to find the shortest word is canceled. It should be:

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

      

That is, if your current word length is less than your previous shortest word length, overwrite it.



Also, instead of starting with blank String

, start with the first word i.e. words[0]

... Otherwise, an 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]

      

+5


source


Invalid if statement. This should work.



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);

      

+2


source


Here's a version using the Java 8 Stream API :

String sentence = "PROGRAMMING IS FUN";
List<String> words = Arrays.asList(sentence.split(" "));

String shortestWord = words.stream().min(
                                     Comparator.comparing(
                                     word -> word.length()))
                                    .get();

System.out.println(shortestWord);

      

You can also sort more complex objects by any of their attributes: if you have a pair Person

and want to sort by lastName

, shortest first, the code would look like this:

Person personWithShortestName = persons.stream().min(
                                                 Comparator.comparing(
                                                 person -> person.lastName.length()))
                                                .get();

      

0


source


Java 8 made things easier. Convert the array String

to a list and use it sorted()

to compare and sort the list in ascending order. Finally, use findFirst()

to get the first value of your list (which is the shortest after sorting).

look,

String[] words = new String[]{"Hello", "name", "is", "Bob"};
String shortest = Arrays.asList(words).stream()
      .sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1)
      .findFirst().get();

System.out.println(shortest);

      

0


source







All Articles