Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches While Loops

Shazada Khan
Shazada Khan
4,789 Points

Please check my code that checks whether the Tower is on the Path

Here is my code

public Tower(MapLocation location,Path path)
{
      for(int i = 0; i < path.Length; i++)
    { 
         MapLocation path_t = path.GetLocationAt(i);

          if (location.x == path_t.x && location.y == path_t.y)
     {
          throw new OutofBoundsException("Towers cannot be placed on the path");
     }
           else {   _location = location; 
                  }  
}
}

This is the constructor written for the Tower class. I just created a test object MapLocation called path_t that checked against each item in the array and initialized _location to location if it didn't match any path_t coordinates.

1 Answer

Steven Parker
Steven Parker
231,198 Points

That looks like it will work, but you don't need to keep setting _location over and over in the loop. Just set it after the loop has finished.

Shazada Khan
Shazada Khan
4,789 Points

Awesome! Thank you and will do.

Jun Dong
Jun Dong
4,754 Points

Is it okay to put the

_location = location;

statement after the for loop because wouldn't the code stop running after the exception is thrown?