Search code examples
javanetbeansrandomintgenerated

How to generate random number in NetBeans?


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.

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

Solution

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

    import java.util.Random;
    

    while the fully qualified class name is java.util.Random like

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

    Also, for a number in the range 1 - 100 you need

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

    Because nextInt(int) (per the Javadoc)

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