| 管理

 站点日历

 

 

 最新评论

 

 友情连接

 

站点统计

 

返回学习相关
JAVA问题1 [2005-3-8] lala 发表在 学习相关
import java.util.*;
import javax.swing.*;

public class LotteryDrawing

{
public static void main(String[] args)
{
String input=JOptionPane.showInputDialog
("How many numbers do you need draw:");
int k=Integer.parseInt(input);

input=JOptionPane.showInputDialog
("What is the highest number you can draw?");
int n=Integer.parseInt(input);

int[] numbers=new int[n];
for (int i=0;i<numbers.length ;i++ )
numbers[i]=i+1;

int[] result=new int[k];
for (int i=0;i<result.length ;i++ )
{
int r=(int)(Math.random()*n);
result[i]=numbers[r];
numbers[r]=numbers[n-1];
n--;
}
Arrays.sort(result);
System.out.println
("Bet the following combination.It'll make you rich!");
for(int i=0;i<result.length;i++)
System.out.println(result[i]);

System.exit(0);
}
}
不明白为什么这句numbers[r]=numbers[n-1];n--;就可以保证不再抽到已经抽过的数字,这个式子的意思不是说将数组最后一个数字改写numbers[r],并把数组长度n减1。我不明白的是,如果第一次就抽到最后一个数字,那不就会重复抽到么?



≡≡≡≡≡ 评论(共  条) 我要评论
{CommentAuthor}{CommentTime} 发表评论 | {CommentUrl}
{CommentContent}

返回顶部





Powered by 5DBLog Design by JKF