java 如何在 NetBeans 中生成随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30447879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:07:53  来源:igfitidea点击:

How to generate random number in NetBeans?

javanetbeansrandomintgenerated

提问by Ben

I'm trying to generate a random between 1 and 100 in NetBeans, but what I used before in Eclipse isn't working. I can't seem to use Random, as it is underined in red: "cannot find symbol." Please show me how.

我试图在 NetBeans 中生成 1 到 100 之间的随机数,但我之前在 Eclipse 中使用的不起作用。我似乎无法使用 Random,因为它用红色下划线表示:“找不到符号。” 请告诉我怎么做。

Random x = new Random();
int n = x.nextInt(100);//random number 1-100

回答by Elliott Frisch

Either use the fully qualified class name (or add an import). The importmight look something like,

要么使用完全限定的类名(或添加一个import)。在import可能看起来像,

import java.util.Random;

while the fully qualified class name is java.util.Randomlike

而完全限定的类名java.util.Random就像

java.util.Random x = new java.util.Random();

Also, for a numberin the range 1 - 100 you need

此外,对于number1 - 100 范围内的a ,您需要

// int n = x.nextInt(100);//random number 1-100
int n = 1 + x.nextInt(100);

Because nextInt(int)(per the Javadoc)

因为nextInt(int)(根据 Javadoc)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

返回一个伪随机的、均匀分布在 0(含)和指定值(不含)之间的 int 值

回答by Juned Ahsan

Most likely you are missing the import:

您很可能错过了导入:

import java.util.Random;

回答by Noob From Mars

For all errors like "cannot find symbol.", you can quickly hit Ctrl + Shift + Ito import all missing library (in Eclipse it is Ctrl + Shift + O). You also should search on the Internet for this error first, the answer everywhere.

对于诸如“ cannot find symbol.”之类的所有错误,您可以快速Ctrl + Shift + I导入所有丢失的库(在 Eclipse 中是Ctrl + Shift + O)。你也应该先在互联网上搜索这个错误,到处都有答案。

回答by Saheb Swaich

This is how to make it generate a random number, I know it is longer but its much easier to understand.

这是如何让它生成一个随机数,我知道它更长但更容易理解。

import java.util.Random;
class (INSERTCLASSNAME){
    public static void main(String[] args){
        Random random = new Random();
        int number;
        for(int counter=1; counter<=1;counter++){
        number = 1+random.nextInt(100);
        System.out.println(number);
        }
    }
}