亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

生成隨機字符串,歡迎指教

package?com.imooc;

import?java.util.ArrayList;
import?java.util.Collections;
import?java.util.Random;

public?class?CollectionSort?{
	ArrayList<String>?RandomList?=?new?ArrayList<String>();
/**
?*?向ArrayList中添加字符串
?*/
	public?void?addList()?{
		String?str;
		for?(int?i?=?0;?i?<?10;?i++)?{
			do?{
				str?=?getString();
			}?while?(RandomList.contains(str));
			RandomList.add(str);
			System.out.println("成功添加:"+str);
		}
	}
/**
?*?排序
?*/
	public?void?sortCollection()?{
			System.out.println("--------排序前--------");
			for?(String?string?:?RandomList)?{
				System.out.println("隨機數列:"+string);
			}
			System.out.println("--------排序后--------");
			Collections.sort(RandomList);
			for?(String?string?:?RandomList)?{
				System.out.println("隨機數列:"+string);
			}
	}
/**
?*?生成長度10以內的隨機字符串
?*?@return
?*/
	public?String?getString()?{
		Random?random?=?new?Random();
		String?str?=?"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST";
		StringBuilder?sb?=?new?StringBuilder();
		int?length?=?str.length();
		do?{
			int?ran?=?random.nextInt(length);
			sb.append(str.charAt(ran));
		}?while?(sb.length()?<?random.nextInt(10));
		return?sb.toString();

	}
	//生成3個1000以內的不重復的數字
	public?void?third(){
		int?i?=?1;
		Random?random?=?new?Random();
		int[]?id?=new?int[3];
		id[0]=random.nextInt(1000);
		while(i<3){
			if(id[i]?!=?random.nextInt(1000)){
				id[i]?=?random.nextInt(1000);
			}else{
				continue;
			}?
				i++;
		}
		for?(int?j?:?id)?{
			System.out.println(j);
		}
	}
	

	public?static?void?main(String[]?args)?{
			CollectionSort?cs?=?new?CollectionSort();
			cs.addList();
			cs.sortCollection();
//			cs.third();
	}

}


正在回答

1 回答

樓主,你的third()方法好像有點問題...你把代碼中的“1000”改為“10”,運行會出現重復數字!

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
Java入門第三季
  • 參與學習       409767    人
  • 解答問題       4543    個

Java中你必須懂得常用技能,不容錯過的精彩,快來加入吧

進入課程

生成隨機字符串,歡迎指教

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號