【问题标题】:How can I specify the range of a random number?如何指定随机数的范围?
【发布时间】:2011-12-26 23:02:50
【问题描述】:

我有随机插入数字的二叉搜索树代码。每次都可以修改大小,但我想修改数字的范围,例如:我希望随机数只有一位或两位。

我该怎么做?

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));
}

【问题讨论】:

  • 你试过什么?既然您知道如何使用 nextInt,似乎将其保持在一定范围内应该很容易。

标签: java range binary-search-tree


【解决方案1】:

怎么样:

  • 只有一位数

    random.nextInt(10)
    
  • 只有两位数

    random.nextInt(90) + 10
    

还是我误解了你的问题?

【讨论】:

  • 如果这个答案解决了你的问题,Totoo Boo,那么请接受它作为答案,以便 Jakub 获得适当的信任。
猜你喜欢
  • 1970-01-01
  • 2019-04-28
  • 2015-07-21
  • 2013-01-07
  • 2021-06-20
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2015-10-24
相关资源
最近更新 更多