从 for 循环 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;        
}

我尝试从循环中附加值的代码:

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

我很想实现相同的输出,但我没有从点内的 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);
}

最新更新