Java 如何从值列表中获取一条语句中的随机数;
给定下面的代码,我必须找到一种方法从这些值中获得一个随机值:100120140160180200220240260280。问题是我必须编写一条语句(一个分号),随机选取一个int并将其分配到random_int变量中。有人知道我如何创建上面的数字列表或数组,并从这些数字中选择一个随机整数,在一个语句中分配给随机整数吗?谢谢你的帮助Java 如何从值列表中获取一条语句中的随机数;,java,random,Java,Random,给定下面的代码,我必须找到一种方法从这些值中获得一个随机值:100120140160180200220240260280。问题是我必须编写一条语句(一个分号),随机选取一个int并将其分配到random_int变量中。有人知道我如何创建上面的数字列表或数组,并从这些数字中选择一个随机整数,在一个语句中分配给随机整数吗?谢谢你的帮助 public static void main(String[] args) { Random random = new Random(); i
public static void main(String[] args) {
Random random = new Random();
int random_int;
// Your single statement goes here
System.out.println(“Number is: “ + random_int);
}
将它们全部放入一个数组中,并随机分配数组的索引。所有这些都可以在一条语句中完成:
public static void main(String[] args) {
Random random = new Random();
int random_int = new int[]{100, 120, 140, 160, 180, 200, 220, 240, 260, 280}[random.nextInt(10)];
System.out.println("Number is: " + random_int);
}
您可以使用
数组
类从数组创建集合
System.out.println(Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280).
get(new Random().nextInt(10)));
您可以执行以下操作:
public static void main(String[] args) {
Random random = new Random();
List<Integer> integerList = Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280);
System.out.println(integerList.get(random.nextInt(integerList.size())));
}
publicstaticvoidmain(字符串[]args){
随机=新随机();
List integerList=Arrays.asList(100、120、140、160、180、200、220、240、260、280);
System.out.println(integerList.get(random.nextInt(integerList.size()));
}
nextInt(10)
将给出0..9。(9=(280-100)/20)
这是一个看到所需数字的规律性的问题:步骤20,从100开始到280
可能是一道考试题。公共课Foo{
公共静态void main(字符串[]args){
对于(int i=0;i
下面给出的语句可以是执行此任务的单个语句:
random_int = List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280)
.get(random.nextInt(List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280).size()));
说明:
0
(包含)和bound
(独占)之间的int
值你试过编译吗?我试过了,有什么问题吗?什么JDK,不适合我编译。在你的编辑之后,它是好的。请不要只发布代码作为答案,还要解释你的代码是做什么的,以及它是如何解决问题的。带有解释的答案通常更有帮助,质量也更好,更有可能吸引更多的选票。谢谢大家的建议!
public class Foo {
public static void main(String[] args) {
for (int i = 0; i < NUMBERS.size(); i++)
System.out.println(getRandomNumber());
}
private static final List<Integer> NUMBERS = Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280);
public static int getRandomNumber() {
Collections.shuffle(NUMBERS);
return NUMBERS.get(0);
}
}
random_int = List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280)
.get(random.nextInt(List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280).size()));