2

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

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

4

4 回答 4

5

你快到了,但是你检测最短单词的比较是相反的。它应该是:

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]
于 2012-09-08T00:15:36.207 回答
2

你的 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);
于 2012-09-08T00:16:30.340 回答
0

这是一个使用 Java 8 的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);

您还可以通过它们的任何属性对更复杂的对象进行排序:如果您有几个Persons 并且您想按它们的 s 对它们进行排序lastName,最短的优先,代码变为:

Person personWithShortestName = persons.stream().min(
                                                 Comparator.comparing(
                                                 person -> person.lastName.length()))
                                                .get();
于 2014-12-27T23:37:54.360 回答
0

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);
于 2015-02-03T20:54:54.370 回答