课后习题! 代码21行的字符串是否需要! 麻烦大神们帮忙看看!
package com.imooc.student; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class RandomString { private List<String> list ; public RandomString(){ this.list= new ArrayList<String>(); } public void stringRandom(){ String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random random = new Random(); int length=0; for(int i=0;i<10;i++){ String str=""; do { str=""; length=random.nextInt(9)+1; for(int j=0;j<length;j++){ char cr=string.charAt(random.nextInt(string.length()-1)); str+=cr; } } while (list.contains(str)); list.add(str); } } public void stringSort(){ System.out.println("排序前:"); for (String string : list) { System.out.println(string); } Collections.sort(list); System.out.println("排序后:"); for (String string : list) { System.out.println(string); } } public static void main(String[] args) { RandomString rs = new RandomString(); rs.stringRandom(); rs.stringSort(); } }
当list.contains(str)判断为true的时候!如果str语句不清空的话!str语句是不是会在重复的基础上增加! 这样是不是会超过规定的长度了!虽然几率很小! 但是这也是有可能的吧!