如何指定数字范围?

时间:2011-12-28 00:03:37

标签: java range binary-tree

  

可能重复:
  How can I specify the range of a random number?

我有二进制搜索树的代码

public static void main(String[] args) throws IOException {
    Random random = new Random();


    Tree theTree = new Tree();


    List<Integer> numbers = new ArrayList<Integer>();
    for (int i = 0; i < 10000; i++) {
        numbers.add(i + 1);
    }

    // re-order number, so it seem like random generator
    Collections.shuffle(numbers);

    // inserting into tree
    long start = System.currentTimeMillis();
    for (int no : numbers) {
        theTree.insert(no, 1.5);
    }
    long end = System.currentTimeMillis();
    System.out.println("Inserting 100 number in tree takes: " + (end - start) + " milliseconds");
    System.out.println("\n\n");

我想指定随机数范围。我想只是一位数,然后只是2位数,然后只有4位数。

1 个答案:

答案 0 :(得分:0)

Totoo,你读过JavaDocs for Random吗?以下代码显示了如何利用Random来执行此操作。

    Random random = new Random();

    int oneDigit = random.nextInt( 10 );
    int twoDigit = 10 + random.nextInt( 90 );
    int threeDigit = 100 + random.nextInt( 900 );
    int fourDigit = 1000 + random.nextInt( 9000 );

    System.out.println( String.format(
            "oneDigit: %d, twoDigit: %d, threeDigit: %d, fourDigit: %d",
            oneDigit,
            twoDigit,
            threeDigit,
            fourDigit ) );