java怎么随机输入四种花色_输入n种口味随机输出四种不同的口味!

#用到了一个Random的类。

import java.util.Random;

public class GetIceCream {

public static void main(String[] args) {

String[] iceCream = new String[] { "香蕉", "草莓", "香芋", "巧克力", "奶油", "咖啡" };//可以换成不同数量的口味

String[] getIceCream = getIce(iceCream);

System.out.println();

System.out.print("随机四种口味: ");

for (int i = 0; i < getIceCream.length; i++) {

System.out.print(getIceCream[i] + " ");

}

}

public static String[] getIce(String[] iceCream) {

String[] getIceCream = new String[4];

boolean[] autoGet = new boolean[6];// 创建使用状态

Random rand = new Random();// 随机取下标

for (int num = 0; num < getIceCream.length; num++) {

int a = rand.nextInt(autoGet.length);

if (!autoGet[a]) {//判断是否为false,如果为true,则退回上一个,再循环

getIceCream[num] = iceCream[a];

// System.out.print(a+" ");

autoGet[a] = true;// 选中的改为true

} else { //衔接上方

num--;

}

}

// 获取什么口味没被选中

for (

int i = 0; i < autoGet.length; i++) {

System.out.print(iceCream[i] + " ");

System.out.print(autoGet[i] + " ");

}

return getIceCream;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值