How can I specify the range of a random number?

2019-03-06 01:44发布

问题:

I have binary search tree code that inserts numbers randomly. I can modify size each time, but I want to modify the range of numbers, for example: I want the random number be just one digit or just 2 digits.

How can I do that?

public static void main( String[ ] args ) {

    BinarySearchTree bst = new BinarySearchTree( );
    Random random = new Random( System.currentTimeMillis() );
    int[] randoms = new int[1000];
    Random randGen = new Random();

    for(int i = 0; i < randoms.length; i++)
    {
        bst.insert( random.nextInt( randoms.length ) );
    }

    System.out.println( "\n sorted :" );

    bst.inorderTraversal( );
    bst.delete (4);

    System.out.println( "\nMax Value:" ); 
    System.out.println(bst.maxValue());
    System.out.println( "\n Min Value:" );
    System.out.println(bst.minValue());

    System.out.println(bst.lookup(1));
}

回答1:

How about:

  • just one digit

    random.nextInt(10)
    
  • just 2 digits

    random.nextInt(90) + 10
    

Or did I misunderstand your question?