Java:查找字符串中的最短单词并将其打印出来

我是Java的新手。 我参加了C课,所以我试图摆脱这种思维模式。 我正在编写的程序有一个部分,用户输入一个整数, n ,然后输入n个单词。 然后,此部分搜索这些单词并找到最短的单词,然后将其返回给用户。 例如,输入可能是:

输入: 4 JAVA编程很有趣

输出:

我目前的代码似乎返回错误的单词。 在这种情况下,它返回“PROGRAMMING”,它应该返回“IS”。 我想也许你们都可以指出我正确的方向。

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

为了让你知道我想要做什么,我试图将单词输入一个字符串,“句子”,然后将该字符串分解为数组中的单个单词,“words [],”然后运行for循环通过比较数组中条目的长度来比较字符串。 谢谢您的帮助!

你几乎就在那里,但你检测最短单词的比较是相反的。 它应该是:

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

也就是说,如果您当前单词的长度小于前一个最短单词的长度,则覆盖它。

此外,不是以空String开头,而是从第一个单词开始,即words[0] 。 否则,空字符串将始终短于数组中的任何字符串:

 String[] words = sentence.split(" "); String shortestword = words[0]; for (int i = 1; i < numwords; i++) { // start with 1, because you already have words[0] 

你的if语句错了。 这应该工作。

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

这是一个使用Java 8的Stream API的版本 :

 String sentence = "PROGRAMMING IS FUN"; List words = Arrays.asList(sentence.split(" ")); String shortestWord = words.stream().min( Comparator.comparing( word -> word.length())) .get(); System.out.println(shortestWord); 

您还可以通过它们的任何属性对更复杂的对象进行排序:如果您有几个Person并且您希望按lastName排序它们,那么最短,则代码变为:

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

Java 8使它变得更简单。 将String数组转换为列表,并使用sorted()按升序对列表进行比较和排序。 最后,使用findFirst()获取列表的第一个值(排序后最短)。

看一看,

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