Find the smallest word in a string in Java

I'm trying to find the smallest word in a user entered string. This is what I have so far:

import java.util.*;
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String myText = sc.next();
    String[] myWords = myText.split(" ");
    int shortestLength,shortestLocation;

    shortestLength=(myWords[0]).length();

    shortestLocation=0;

    for (int i=1;i<myWords.length;i++) {
        if ((myWords[i]).length() < shortestLength) {
            shortestLength=(myWords[i]).length();
            shortestLocation=i;
        }
    }
    System.out.println(myWords[shortestLocation]);
}

If I entered "SMALLEST WORD SHOULD BE A", the output should be A but it just gives me the first word of the string. Any ideas?

Answers


Your algorithm is fine, but instead of using next():

String myText = sc.next();

Which will only read a single token, i.e., the first word, use nextLine(), which will read the entire line:

String myText = sc.nextLine();

Need Your Help

Rails: How to use select method to fetch items with certain value in a row of model

ruby-on-rails ruby-on-rails-4

I'm new with ruby on rails and have been stuck no a problem for a while. I'm using rails 4.2.3

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.