(Java随机数举例)随机扔一千次硬币的正反次数

方法一:

public class coin{

public static void main(String args[]){
int n = 0;
int m = 0;
int len = 1000;
int str[] = new int[len];
for(int i = 0 ; i < len ; i ++){
str[i] = ( int )(Math.random()*2);
if(str[i] == 1 ){
n = n + 1;
}else{
m = m + 1;
}
}
System.out.println("正面朝上的次数:"+n);
System.out.println("反面朝上的次数:"+m);
}

}


方法二:

package org.lxh.demo.coin;
import java.util.Random;
public class coin{
public static void main(String args[]){
int n = 0;
int m = 0;
int len = 1000;
int str[] = new int[1000];                 //创建一千个的数组
Random rad = new Random();
for(int i = 0 ; i < len ; i ++){
str[i] = rad.nextInt(2);              //为一千个的数组赋值
if(str[i] == 1 ){
n = n + 1;
}else{
m = m + 1;
}
}
System.out.println("正面朝上的次数:"+n);
System.out.println("反面朝上的次数:"+m);
}
}

 

posted @ 2013-07-20 18:38  javawebsoa  Views(490)  Comments(0Edit  收藏  举报