如何从两个整数中随机选择一个? [英] How to randomly select one from two integers?

查看:79
本文介绍了如何从两个整数中随机选择一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以可以说我想从两个数字( 1 3 )中随机选择.

So lets say I want to randomly choose from the set of two numbers 1 and 3.

我该怎么做?我是否只将 int a 分配给 1 ,将 int b 分配给 3 ,然后从中随机选择> a b ?

How do I go about doing that? Do I just assign int a to 1, int b to 3, and then do randomly select from a and b?

推荐答案

如果只有两个数字可供选择,则可以使用 boolean 的值,因为它会返回true false .

If there are only two numbers to choose from then you can use the value of a boolean, because it returns either true or false.

假设 int a = 1 int b = 3 的单线解决方案:

One-liner solution assuming that int a = 1 and int b = 3:

int randomOfTwoInts = new Random().nextBoolean() ? a : b;

这篇关于如何从两个整数中随机选择一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆