package imooc.com; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; public class RandomString { public void getRandomString(int length){ /** * 根据输入的字符串长度,实现随机生成字符串 * 当字符串不重复时,添加到list * 打印添加成功的List * Collection排序后打印 */ //作为字符串的字符库 String base="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; List <String> stringList=new ArrayList<String>(); Random random=new Random(); //开始随机添加字符串 for(int j=0;j<10;j++){ StringBuffer s=new StringBuffer(); do{ for(int i=0;i<length;i++){ //开始随机添加字符 int getSeq=random.nextInt(base.length()); s.append(base.charAt(getSeq)); } }while(stringList.contains(s.toString())); stringList.add(s.toString()); System.out.println("将要添加:"+s); } System.out.println("----------排序前---------"); for (String string : stringList) { System.out.println("元素:"+string); } //字符串排序啦 Collections.sort(stringList); System.out.println("----------排序后---------"); for (String string : stringList) { System.out.println("元素:"+string); } } public static void main(String[] args) { // TODO Auto-generated method stub //创建输入的Scanner类 Scanner console= new Scanner(System.in); System.out.println("请输入随机生成的字符串长度:"); int length=console.nextInt(); RandomString stringRand=new RandomString(); stringRand.getRandomString(length); } }
very good!