[英]How do I count the characters in a string and then sort them alphabetically?
[英]How do I sort randomly generated characters alphabetically?
这就是我到目前为止
public class RandomCharacter
{
public static char getRandomUpperCaseLetter()
{
int ascii = (int) (Math.random()*26) + (int) 'A';
return (char)ascii;
}
public static char getRandomDigitCharacter()
{
int digit = (int)(Math.random()*10) + (int) '0';
return (char)digit;
}
public static void main(String [] args)
{
for (int i = 1; i <= 100; i++)
{
System.out.print(getRandomUpperCaseLetter());
if(i%10 == 0)
System.out.print("\n");
}
}
}
我不知道如何按字母顺序具体排序,我已经尝试了几个小时,但找不到任何东西。 有人可以使用我的代码来教我这是如何工作的吗?
要对值进行排序,必须先将它们存储在某种数据结构中,例如数组列表,然后再对其进行排序。 然后,如果您使用了可排序的集合(例如数组列表),则可以使用.sort()
方法,列表将被自动排序。 例如/参考: http : //beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/
对于自然排序,您只需在字符串中添加生成的字母,然后调用Collections.sort(listVariable)即可。 这应该可以回答您的问题。
样例程序
import java.util.*;
public class Details {
public static void main(String args[]){
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");
/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
/* Sort statement*/
Collections.sort(listofcountries);
/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.