[英]How do I write a random array of 5 integers but have it not count 0 as an integer?
[英]How do I populate trees with many random integers?
我正在編寫一個程序,該程序應該用1000個隨機值(從0到300)填充10個隨機樹。這是我的測試器類的代碼。 但是,當我運行該程序時,它為每棵樹打印出完全相同的內容,而在代碼方面,它看起來就像我在添加不同的隨機數。
我感覺它會不斷增加相同的數字,但是我不知道如何更改它。 我對Random類或Math.random()不太熟悉。
package ch08.trees;
import java.util.ArrayList;
public class BSTTest {
ArrayList<BinarySearchTree<Integer>> trees = new ArrayList<BinarySearchTree<Integer>>();
public BSTTest() {
for(int h = 0; h < 10; h++) { //Populate the arraylist with 10 trees
trees.add(new BinarySearchTree<Integer>());
}
for(int i = 0; i < 10; i++) //Run through 10 trees in array
for(int j = 0; j < 1000; j++) { //1000 integers for each tree
trees.get(i).add((int) Math.random()*300);
}
}
public String toString() {
String s = "";
for(int i = 0; i < 10; i++) {
int height = trees.get(i).height();
int optimal = trees.get(i).optimal();
double ratio = (double) height/(double) optimal; //Ratio only useful when decimal
s += "Tree " + i + "--" + "Height: " + height + ", Optimal Height: " + optimal +
", Bushyness Ratio: " + ratio + "\n";
}
return s;
}
public static void main(String[] args) {
BSTTest a = new BSTTest();
System.out.println(a);
}
}
Math.random返回一個介於0.0和1.0之間的雙精度值,因此強制轉換為int是錯誤的。
就像做0 * 300
或1 * 300
==不太隨機。
如果您要乘以300.00,結果將大不相同。
另外考慮http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
在內存中保留一個Random
實例,然后調用nextInt
#nextInt()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.