我有一个如何做到这一点的基础,但它只做了两个单词,而不是我输入的整个5个单词。(测试这个作为输入:"这是一个测试消息")。我们被允许使用String str ="这是一个测试消息&#34 ;; String [] tokens = str.split("");请帮忙! (忽略括号中的单词,我需要更多的单词来发布这个)
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Enter a String:");
String enter = console.nextLine();
String[] toke = enter.split(" ");
for(String retrieve: toke)
{
System.out.println(retrieve);
}
String[] group = new String[toke.length];
for(int a = 0; a < group.length; a++)
{
group[a] =" ";
}
for(int a = 0; a < toke.length; a++)
{
for(int b =0; b< group.length; b++)
{
if(toke[a].length() > group[b].length())
{
for(int c = 0; c < b; c++)
{
if(b + a < group.length)
{
group[c + b] = group[c + b + 1];
for(int d = 0; d < c; d++)
{
if(b + c <= group.length)
{
group[d + c] = group[d + c + 1 ];
}
}
group[c + b + 1] = toke[a] + group[a];
}
}
group[b] = toke[a];
break;
}
}
}
System.out.println("The Sorted Tokens in Descending Order:");
for(String retrieve: group)
{
System.out.println(retrieve);
}
}
}
答案 0 :(得分:1)
你不能只使用Arrays.sort();
这是一个例子,
Scanner scan = new Scanner(System.in);
String[] line = scan.nextLine().split(" ");
Arrays.sort(line); //if you want from smallest -> biggest
Collections.reverse(Arrays.asList(line)); // if you want biggest -> smallest, add this.
for(String s : line){
System.out.print(s + " ");
}
答案 1 :(得分:0)
可能会有所帮助:
public static void main(String[] args) {
// TODO code application logic here
Scanner console = new Scanner(System.in);
System.out.println("Enter a String:");
String enter = console.nextLine();
String[] toke = enter.split(" ");
for(String retrieve: toke){
System.out.println(retrieve);
}
String temp;
for(int i=0; i < toke.length; i++){
for(int j=i+1 ; j<toke.length; j++){
if(toke[i].compareTo(toke[j])>0){
temp=toke[i];
toke[i]=toke[j];
toke[j]=temp;
}
}
}
System.out.println("The Sorted Tokens in Descending Order: ");
for(String retrieve: toke){
System.out.println(retrieve);
}
}