gpt4 book ai didi

java - 从最短单词到最长单词输出一个句子

转载 作者:行者123 更新时间:2023-12-04 16:35:31 31 4
gpt4 key购买 nike

这就是我目前一直在尝试获得这样的输出:

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

如果有人能提供帮助那就太好了!

最佳答案

您可以将输入转换为列表,然后使用 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));

这会打印(对于输入 this is a sentence):

 a is this sentence

关于java - 从最短单词到最长单词输出一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70222965/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com