gpt4 book ai didi

java - 如何随机生成 1 到 50 之间的整数 (java)

转载 作者:行者123 更新时间:2023-12-01 11:14:13 24 4
gpt4 key购买 nike

这是完整的代码,我如何在此创建随机数,以便 numberneedingtobeguessed是随机生成的。

public class Guessing {

public static void main(String[] args) {
// TODO Auto-generated method stub

@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int number;
int numberneedingtobeguessed = 26;
int done = 1;

System.out.println("I am thinking of a number in between 1 and 50 what is it?");
while (done < 2) {
number = input.nextInt();

if (number < numberneedingtobeguessed) {
System.out.println("Too low");
}
else if (number > numberneedingtobeguessed) {
System.out.println("Too high");
}
else if (number == numberneedingtobeguessed) {
System.out.println("You guessed correctly");
done = done + 1;
}
}
}
}

最佳答案

import java.util.Random;

.........

Random ran = new Random();
int r = ran.nextInt(50) + 1;

这将生成一个 0 ... 49 之间的随机数,然后在末尾添加 1。

关于java - 如何随机生成 1 到 50 之间的整数 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32027978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com