1. 程式人生 > >Android生成隨機整數

Android生成隨機整數

package cc.test;
 
import java.util.HashSet;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
/**
 * 
 * Demo描述:
 * Java中利用Random生成隨機數
 * 
 */
public class TestRandomActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        testRandom1();
        testRandom2();
        testRandom3();
    }
    
    
    
    //生成隨機數
    private void testRandom1(){
    	Random random=new Random();
    	for (int i = 0; i <5; i++) {
			System.out.println("random.nextInt()="+random.nextInt());
		}
    	
    }
    
    
    
    //在一定範圍內生成隨機數.
    //比如此處要求在[0 - n)內生成隨機數.
    //注意:包含0不包含n
    private void testRandom2(){
    	Random random=new Random();
    	for (int i = 0; i <10; i++) {
			System.out.println("random.nextInt()="+random.nextInt(20));
		}
    	
    }
    
    
    //在一定範圍內生成不重複的隨機數
    //在testRandom2中生成的隨機數可能會重複.
    //在此處避免該問題
    private void testRandom3(){
    	HashSet integerHashSet=new HashSet();
    	Random random=new Random();
    	for (int i = 0; i <10; i++) {
    		int randomInt=random.nextInt(20);
    		System.out.println("生成的randomInt="+randomInt);
    		if (!integerHashSet.contains(randomInt)) {
    			integerHashSet.add(randomInt);
    			System.out.println("新增進HashSet的randomInt="+randomInt);
			}else {
				System.out.println("該數字已經被新增,不能重複新增");
			}
		}
    	
    }
    
}