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]);
}
}
}
如果有人能帮忙,那就太好了
# 1 楼答案
您可以将输入转换为列表,然后使用lambda进行排序:
这将打印(用于输入^{):
# 2 楼答案
//按空格分割单词,然后按长度排序,再按空格连接单词