有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java输出从最短单词到最长单词的句子

这就是我目前一直试图获得的输出,如下所示:

input:  this is a sentence
output: a is this sentence
import java.util.Scanner;
Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentance:");
        String text = input.nextLine();
        String[] words = text.split("");
        String temp;

        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < (words.length - 1); j++) {
                if (words[j].compareTo(words[j + 1]) < 0) {
                    temp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = temp;

                }
            }
            System.out.print(words[i]);
        }
    }
}

如果有人能帮忙,那就太好了


共 (2) 个答案

  1. # 1 楼答案

    您可以将输入转换为列表,然后使用lambda进行排序:

    Scanner input = new Scanner(System.in);
    System.out.print("Enter a sentence:");
    String text = input.nextLine();
    List<String> words = Arrays.asList(text.split(" "));
    words.sort(Comparator.comparingInt(String::length));
    System.out.println(String.join(" ", words));
    

    这将打印(用于输入^{):

     a is this sentence
    
  2. # 2 楼答案

    @Test
        public void testSort() {
            Assertions.assertEquals("a is this sentence", sort("this is a sentence"));
        }
    
        private String sort(String sentence) {
            return Arrays.stream(sentence.split(" "))
                    .sorted(Comparator.comparingInt(String::length))
                    .collect(Collectors.joining(" "));
        }
    

    //按空格分割单词,然后按长度排序,再按空格连接单词