日期:2014-05-19 浏览次数:20919 次
<html>
<head>
<script src="myjs.js"></script>
<script type="text/javascript">
function randomBoll(){
var span1=$("span1");
span1.innerHTML=green().toString();
var span2=$("span2");
span2.innerHTML=red();
}
function contains(boll,green){
for(var i=0;i<green.length;i++){
if(parseInt(green[i])==parseInt(boll)){
return true;
}else{
return false;
}
}
}
function green(){
var green=new Array();
for(i=0;i<6;i++){
var boll=Math.ceil(Math.random()*33);
if(boll==0){
i=i-1;
continue;
}else{
if(contains(boll,green)){
i=i-1;
continue;
}else{
green[i]=boll;
}
}
}
return green;
}
function red(){
var red;
do{
red=Math.ceil(Math.random()*16);
}while(red==0);
return red;
}
</script>
</head>
<body>
<input type="button" value="随机双色球" onclick="randomBoll();">
<br/>
<span>绿球:</span>
<span id="span1"></span>
<br/>
<span>红球:</span>
<span id="span2"></span>
</body>
</html>
----
myjs.js
function $(id){
return document.getElementById(id);
}
--
------解决方案--------------------
package cn;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class TwoColorBall {
private String periods;
private Set<Integer> redBall = new HashSet<Integer>();//排序的话可以考虑用SortedSet
private Integer blueBall;
//构造一期中奖的号码
public TwoColorBall(String periods) {
this.periods = periods;
Random random = new Random();
while(true) {
Integer red = random.nextInt(34) + 1;
redBall.add(red);
if(redBall.size() >= 7) {
break;
}
}
blueBall = random.nextInt(14) + 1;
System.out.println("红球为:");
for(Integer i : redBall) {
System.out.println(i);
}
System.out.println("蓝球为:" + blueBall);
}
public String getPeriods() {
return periods;
}
public void setPeriods(String periods) {
this.periods = periods;
}
public Set<Integer> getRedBall() {
return redBall;
}
public void setRedBall(Set<Integer> redBall) {
this.redBall = redBall;
}
public Integer getBlueBall() {
return blueBall;
}
public void setBlueBall(Integer blueBall) {
this.blueBall = blueBall;
}
//根据传入的参数判断结果
public void winAward(Set<Integer> redSet, Integer blue) {
if(redSet == null || redSet.size() != 7 || blue == null) {//更具需要还可以添加判断
//抛出参数错误的异常
}
int redCount = 0;
int blueCount = 0;//用boolean也可以
for(Integer red : redSet) {
if(this.redBall.contains(red)) {
redCount++;
}
}
if(this.blueBall.equals(blue)) {
blueCount++;
}
System.out.println("恭喜您中了第" + this.periods + "期双色球中的" + redCount + "个红球和" + blueCount + "个蓝球");
}
public static void main(String[] args) {
TwoColorBall ball = new TwoColorBall("111");
ball.winAward(ball.getRedBall(), ball.getBlueBall());
ball.winAw