抢红包:
一个大V直播发起了抢红包活动,分别有:9,666,188,520,99999五个红包.请模拟粉丝抽奖,按照先来先得,随机抽取,抽完即止,注意:一个红包只能被抽一次,先抽或后抽哪一个红包都是随机的,示例如下(不一定是下面的顺序):
*将抽奖后的数组位置往前移,最后一位补0
public static void main(String[] args) {
int[] arr = {9, 666, 188, 520, 99999};
for (int i = 0; i < arr.length; i++) {
Random r = new Random();
System.out.print("按任意键完成抽奖:");
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
int index = r.nextInt(arr.length - i);
System.out.println("恭喜您抽中了" + arr[index]);
if (arr.length - 1 == i) {
System.out.println("活动结束....");
break;
}
getArrayByIndex(arr, index);
}
}
public static void getArrayByIndex(int[] arr, int index) {
for (int i = 0; i < arr.length - 1; i++) {
if (i >= index) {
arr[i] = arr[i + 1];
}
}
arr[arr.length - 1] = 0;
}
*将抽奖后的剩余的元素组成新数组
public static void main(String[] args) {
int[] arr = {9, 666, 188, 520, 99999};
Random r = new Random();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("请按任意键完成抽奖");
String key = sc.nextLine();
int index = r.nextInt(arr.length);
int number = arr[index];
System.out.println("恭喜您,抽中了" + number);
if (i == 4) {
System.out.println("活动结束...");
break;
}
arr = getArrayByIndex(arr, index);
}
}
public static int[] getArrayByIndex(int[] arr, int index) {
int[] result = new int[arr.length - 1];
for (int i = 0; i < result.length; i++) {
if (i < index) {
result[i] = arr[i];
} else {
result[i] = arr[i + 1];
}
}
return result;
}
标签:index,arr,int,抢红包,System,length,out
From: https://www.cnblogs.com/OKGOsky/p/17003073.html