2

This is one of the first programs I am writing by myself. I want to make a physics calculator where many objects can interact with each other and give the user an option to add more objects. My idea is to have a for loop that runs through each object pulling on each other like this.

for(int n=1; n<=totalObjs; n++){
    objName = "object"+n;
    for(int i=1; i<n; i++){
        obj2Name = "object"+i
        objName.getMass();
        //getting mass and position from both
        //calculations here}
   for(int x=n+1; x<=totalObjs; x++){
      //same stuff as in the previous for loop}
}

I know there are probably huge syntax errors or logical errors in that but I'd like to sort through those on my own. Is there some way i could reference objects with the strings?

1 Answer 1

2

Is there some way i could reference objects with the strings?

Yes, via a Map<String, SomeType> such as a HashMap<String, SomeType>.

Think of this as being similar to an array or ArrayList, but instead of using number indices, you'd be using String indices.

Now looking at your code however, you might be better off using a simple ArrayList or array, since you appear to be trying to use numeric indices.

e.g.,

// assume a class called GravMass which has Mass, position, and momentum
List<GravMass> gravMassList = new ArrayList<GravMass>();

// fill your list

for(int i = 0; i < gravMassList.size() - 1; i++) {
    GravMass gravMass1 = gravMassList.get(i);
    int mass1 = gravMass1.getMass();
    for(int j = i + 1; j < gravMassList.size(); j++){
        GravMass gravMass2 = gravMassList.get(j);
        int mass2 = gravMass2.getMass();
        //getting mass and position from both
        //calculations here}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.