anaqwer
anaqwer

Reputation: 23

How can I print the longest word from a user defined list?

I have this code to print the longest word in a user defined list but i get null as the result. I have converted the list to a string but it still does not work.

public class no7 {

  public static String getLongestString(String[] array) {
      int maxLength = 0;
      String longestString =null;
      for (String s : array) {
          if (s.length() > maxLength) {
              maxLength = s.length();
              longestString = s;
          }
      }
      return longestString;
  }

  public static void main(String[] str) {


      Scanner in = new Scanner(System.in);
    System.out.println("Enter a list:");
    ArrayList<String> list = new ArrayList<String>();
     str = list.toArray(new String[0]);


     while (!in.hasNext("done") && !in.hasNext("Done") )
        {
        list.add(in.next());
        }

     String longestString = getLongestString(str);
      System.out.format("longest string: '%s'\n", longestString);



        }
  }

Upvotes: 0

Views: 773

Answers (3)

sleepToken
sleepToken

Reputation: 1847

Forget messing with main args - and there's also no need to track the maxLength. String.length() already does that for you.

Don't forget to close your scanner. :~p

Edit: If you want to print the ties, you can store each word in a HashMap mapping lenghts -> words.

For example:

3 -> "cat", "dog"
4 -> "door", "tree", "frog"

Now we can find the largest key (4) and return the list of those words.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a list:");

        ArrayList<String> list = new ArrayList<String>();

        while(!in.hasNext("done") && !in.hasNext("Done")) {
            list.add(in.next());
        }

        String longestString = getLongestString(list);
        System.out.format("longest string: '%s'\n", longestString);

        in.close();
    }

     public static String getLongestString(ArrayList<String> array) {
         Map<Integer, List<String>> lengths = new HashMap<Integer, List<String>>();

          // Put each word in the HashMap, mapped by its length
          for (String s : array) {
              if (lengths.get(s.length()) == null) {
                  lengths.put(s.length(), new ArrayList<String>());
                  lengths.get(s.length()).add(s);
              } else {
                  lengths.get(s.length()).add(s);
              }
          }

          // Store the entry with the longest length
          Map.Entry<Integer, List<String>> maxEntry = null;

          for (Map.Entry<Integer, List<String>> entry : lengths.entrySet()) {
              if (maxEntry == null || entry.getKey() > maxEntry.getKey()) {
                  maxEntry = entry;
              }
          }

          return maxEntry.getValue().toString().replace("[","").replace("]", "");
      }
}

Upvotes: 1

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4339

The answers provided by Federico klez Culloca and sleepToken are valid, I just want to clear your code a bit more, paying attention to the following:

  • Use try with resources to open and automatically close your Scanner.

  • Prefer referencing objects by their interfaces. Even if you create an instance of ArrayList<String> it's preferable to assign the result to List<String>.

  • Your code fails at detecting the end of input stream. You check for presence of the word 'done' or 'Done', but don't check if any word is available at all. If the stream is closed without sending 'done' or 'Done' then your program stops with an exception.

  • You can get the string with a maximum length using a one-liner with Java stream API.

  public static String getLongestString(List<String> strings) {
    return strings.stream().max(Comparator.comparingInt(String::length)).orElse(null);
  }

  public static void main(String[] str) {
    System.out.println("Enter a list:");
    try (Scanner in = new Scanner(System.in)) {
      List<String> list = new ArrayList<>();
      while (in.hasNext()) {
        String next = in.next();
        if ("done".equalsIgnoreCase(next)) {
          break;
        }
        list.add(next);
      }
      String longestString = getLongestString(list);
      System.out.format("longest string: '%s'%n", longestString);
    }
  }

Upvotes: 2

Federico klez Culloca
Federico klez Culloca

Reputation: 27159

First of all, public static void main(String[] str) { and then str = list.toArray(new String[0]); that's not what main's parameter is for, FYI.

Also, str will not contain what the user inputs if you assign to str the content of the list before filling the list itself.

Finally, why can't getLongestString simply accept and work with a List instead of an array? You're accessing it sequentially anyway.

All of this translates to

public class no7 {

    public static String getLongestString(List<String> array) {
        int maxLength = 0;
        String longestString =null;
        for (String s : array) {
            if (s.length() > maxLength) {
                maxLength = s.length();
                longestString = s;
            }
        }
        return longestString;
    }

    public static void main(String[] str) {


        Scanner in = new Scanner(System.in);
        System.out.println("Enter a list:");
        ArrayList<String> list = new ArrayList<String>();    

        while (!in.hasNext("done") && !in.hasNext("Done") )
        {
            list.add(in.next());
        }

        String longestString = getLongestString(list);
        System.out.format("longest string: '%s'\n", longestString);



    }
}

As a side note, no7 for a class name does not respect the java naming convention. It should be No7 (remember to rename the file accordingly).

Upvotes: 2

Related Questions