我试着编写一个程序,先对给定的字符串逐个排序,然后对所有字符串按降序排序。我设法按字符对字符串进行排序,但在按字符对所有已排序的字符串进行排序时遇到了问题。我尝试使用array.sort(),但它没有递减排序,它只对第一个输入排序,而不是已经排序的数组
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j< chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
String[] SortedString = new String[5];
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
Arrays.sort(SortedString);
for (int counter = 0; counter<5; counter++)
{
System.out.println(SortedString[counter]);
}
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
UserInput.close();
Arrays.sort(names);
for (int counter = 0; counter<5; counter++)
{
sortString(names[counter]);
}
}
}
1条答案
按热度按时间dldeef671#