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 i
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]
Java 8 has made it simpler. Convert your String
array to a list and use sorted()
to compare and sort your list in ascending order. Finally, use findFirst()
to get the first value of your list (which is shortest after sorting).
have a 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);
Your if statement is wrong. 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);
Here's a version that makes use of Java 8's 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 attribute: If you have a couple of Person
s and you wanted to sort them by their lastName
, shortest first, the code becomes:
Person personWithShortestName = persons.stream().min(
Comparator.comparing(
person -> person.lastName.length()))
.get();