0

I'm still a newbie in Java. What I want to do here is to assign the values from the for loop into an array.

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:

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. Any help is appreciated.

Thank you very much.

1
  • 2
    So what is the point of i<noOfNodes-(noOfNodes-1) this is always 1 so why have a loop at all? Commented May 18, 2020 at 22:54

1 Answer 1

2

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.

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thank you very much for your explanation, sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.