简体   繁体   English

从 for 循环 java 分配数组的值

[英]Assign values of array from for loop java

I'm still a newbie in Java.我还是 Java 的新手。 What I want to do here is to assign the values from the for loop into an array.我在这里要做的是将for循环中的值分配到一个数组中。

Here is a hardcoded example of what I wanted to achieve:这是我想要实现的硬编码示例:

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

The code that I'm trying to append the values from the loop:我试图 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;
}

I would love to achieve the same output but I'm not getting the values from the for loop array inside points.我很想实现相同的 output 但我没有从点内的 for 循环数组中获取值。 Any help is appreciated.任何帮助表示赞赏。

Thank you very much.非常感谢。

You have a few mistakes in your code.您的代码中有一些错误。 You're using floats instead of integers, which doesn't make sense here, you're not assigning any values to your points array, and that outer for-loop is useless, since it will run exactly once, because your condition is i < noOfNodes - (noOfNodes - 1) , which is the same as i < 1 .您使用的是浮点数而不是整数,这在这里没有意义,您没有为points数组分配任何值,并且外部 for 循环是无用的,因为它只会运行一次,因为您的条件是i < noOfNodes - (noOfNodes - 1) ,与i < 1相同。

Here is one way to fill that array up with randomly generated values.这是用随机生成的值填充该数组的一种方法。

//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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM