[英]Assign values of array from for loop java
我還是 Java 的新手。 我在這里要做的是將for循環中的值分配到一個數組中。
這是我想要實現的硬編碼示例:
public class Nodes {
private int noOfNodes;
private Points[] points;
Nodes(){
}
Nodes(int noOfNodes){
this.noOfNodes = noOfNodes;
Points[] points = {
new Points("A", 100, 200),
new Points("B", 200, 300),
new Points("C", 300, 400),
new Points("D", 650, 650),
new Points("E", 500 , 600)
};
this.points=points;
}
我試圖 append 來自循環的值的代碼:
Points [] points = new Points[this.noOfNodes];
for(int i=0; i<noOfNodes-(noOfNodes-1); i++){
//randomly generate x and y
float max = 1000;
float min = 1;
float range = max - min + 1;
for (int j=0; j<noOfNodes; j++){
String name = Integer.toString(noOfNodes);
float x = (float)(Math.random() * range) + min;
float y = (float)(Math.random() * range) + min;
}
}
this.points=points;
}
我很想實現相同的 output 但我沒有從點內的 for 循環數組中獲取值。 任何幫助表示贊賞。
非常感謝。
您的代碼中有一些錯誤。 您使用的是浮點數而不是整數,這在這里沒有意義,您沒有為points
數組分配任何值,並且外部 for 循環是無用的,因為它只會運行一次,因為您的條件是i < noOfNodes - (noOfNodes - 1)
,與i < 1
相同。
這是用隨機生成的值填充該數組的一種方法。
//outside your constructor
private static final int max = 1000, min = 1;
//in your constructor
this.points = new Points[noOfNodes];
for (int i = 0; i < noOfNodes; i ++) {
points[i] = new Point(Character.toString(i + 'A'), (int) (Math.random() * max) - min, (int) (Math.random() * max) - min);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.