如何在java中生成min和max之间的随机整数? [英] How do I generate a random integer between min and max in java?

查看:180
本文介绍了如何在java中生成min和max之间的随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么方法在min和max之间返回一个随机int?或者不存在这样的方法吗?

What method returns a random int between a min and max? Or does no such method exist?

我正在寻找的是这样的:

What I'm looking for is something like this:

NAMEOFMETHOD (min, max) 

(其中min和max int s)

(where min and max are ints)

返回如下内容:

8

(随机)

如果确实存在这样的方法,请将您的答案链接到相关文档。谢谢。

If such a method does exist could you please link to the relevant documentation with your answer. thanks.

更新:尝试在nextInt回答中实现完整解决方案我有这个:

Update: atempting to implement the full solution in the nextInt answer I have this:

class TestR
{
    public static void main (String[]arg) 
    {   
        Random random = new Random() ;
        int randomNumber = random.nextInt(5) + 2;
        System.out.println (randomNumber) ; 
    } 
} 

我仍然从编译器得到相同的错误:

I'm still getting the same errors from the complier:

TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
        ^
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
                            ^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
        int randomNumber = random.nextInt(5) + 2;
                                         ^
TestR.java:6: incompatible types
found   : <nulltype>
required: int
        int randomNumber = random.nextInt(5) + 2;
                                             ^
4 errors

这里出了什么问题?

推荐答案

在应用程序启动时构造一个Random对象:

Construct a Random object at application startup:

Random random = new Random();

然后使用 Random.nextInt(int)

int randomNumber = random.nextInt(max + 1 - min) + min;

请注意,下限和下限均包含在内。

Note that the both lower and upper limits are inclusive.

这篇关于如何在java中生成min和max之间的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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