6

im trying to write a code to take in a group of words, and return the smallest word in character length. pretty simple, for some reason its returning 'bye' when there is a shorter word in there such as 'no'.

public class function2 {

    public static void main(String [] args) {
        String [] SA = {"hello", "goodbye", "jack", "bye", "yes", "no", "yoo"};
        smallest(SA);
        System.out.println("The shortest word is " + smallest(SA));
    }

    public static String smallest(String SA[]) {
        String first = SA[0];
        for (int i = 1 ; i < SA.length ; i++) {
            if ((SA[i].compareTo(first)) < 0) {
                first = SA[i];
            } // if
        } // for
        return first;
    }// smallest
}// lab1b
6
  • shouldnt have left that in there, sorry lol. Commented Sep 14, 2014 at 3:47
  • it compiles, i just cant get the correct return im looking for @Pshemo Commented Sep 14, 2014 at 3:48
  • 1
    Shouldn't you have a check for the string length in there somewhere since that is what you are comparing? Something like if (SA[i].length() < first.length()). Commented Sep 14, 2014 at 3:49
  • if((SA[i].compareTo(first))<0) the compareto function returns a negative number if the string at index i is smaller than the word that first is = to. Commented Sep 14, 2014 at 3:51
  • 2
    @BenjiWeiss That's not what compareTo does. It checks for alphabetical order. Commented Sep 14, 2014 at 3:53

6 Answers 6

9

compareTo doesn't compare length of Strings, but their alphabetic order.

You should change your condition to if (SA[i].length()<first.length()).

Sign up to request clarification or add additional context in comments.

Comments

4

In Java 8, you create a Comparator that will check the length of string which would make the array ascending, convert that list in a stream, and use sorted to sort the array, eventually, use findFirst to return the first element and get() to convert it into a String.

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

Comments

4

Shortest algorithm with Java 8+ using elegant Comparator.comparing method.

final String shortest = List.of("hello", "yes", "no")
                          .stream()
                          .min(Comparator.comparing(String::length))
                          .get();

Comments

3

Your method is close, but your variable names are a bit difficult to read to start you only need to call your method once to print the shortest name (calling it twice searches twice, and discards the first result),

public static void main(String[] args) {
    String[] SA = { "hello", "goodbye", "jack", "bye", "yes", "no", "yoo" };
    System.out.println("The shortest word is " + smallest(SA));
}

Next, it's usually a good idea to test that your input is valid (not null and at least one element). You should also decide how you want to handle those cases, I chose to return ""; below. Finally, you need to check length() the String(s) to get the shortest word. Something like,

public static String smallest(String words[]) {
    if (words == null || words.length < 1) {
        return "";
    }
    String smallest = words[0];
    for (int i = 1; i < words.length; i++) {
        if (words[i].length() < smallest.length()) {
            smallest = words[i];
        }
    }
    return smallest;
}// smallest

Comments

1
import java.util.Comparator;
import java.util.function.Function;

import static java.util.Arrays.asList;

public class Foo {

    public static void main(String[] args) {
        String[] words =
            {"hello", "goodbye", "jack", "bye", "yes", "no", "yoo"};
        System.out.println(shortestWord(words));
    }

    static String shortestWord(String[] words) {
        return asList(words).stream().min(compareBy(String::length)).get();
    }

    static <A, B extends Comparable<B>> Comparator<A> compareBy(
            Function<A, B> f) {
        return (A x, A y) -> f.apply(x).compareTo(f.apply(y));
    }
}

Comments

0

Im not sure what you are trying to do with the method compareTo(), but if you want to keep find the length of a string you use the length() method.

public class function 2
{

    public static void main(String[] args) {
        String [] SA = {"hello" , "goodbye"  , "jack" , "bye" , "yes" , "no" , "yoo"};

        System.out.println("The shortest word is " + smallest(SA));
    }

    public static String smallest(String SA[]) {
        //Keep track of the shortest word by index and length
        int index = 0, minLength = SA[0].length();
        for (int i = 1; i < SA.length; i++){
            //if the next string is smaller in length then we save that index and length in our variables
            if(SA[i].length() < minLength){
                index = i;
                minLength = SA[i].length();  
            }           
        }
        //returns the smallest word
        return SA[index];
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.