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 trialJavier Gandia
Full Stack JavaScript Techdegree Student 9,153 Pointshttps://teamtreehouse.com/library/c-objects/methods/using-static-methods
I am using Visual Studios to write these codes.. I am writing everything where it belongs exactly how it is in the video.. but when i run it, it gives me an answer of 7. On the video it gives him "3". why is this?
class Game
{
static void Main(string[] args)
{
Map map = new Map(8, 5);
Point point = new Point(4, 2);
Console.WriteLine(point.DistanceTo(5, 5));
Console.ReadLine();
}
}
}
Everything on the point class is exactly as he wrote it also.. class Point { public readonly int X; public readonly int Y;
public Point(int x, int y)
{
x = X;
y = Y;
}
public int DistanceTo(int x, int y)
{
int xDiff = X - x;
int yDiff = Y - y;
int xDiffSquared = xDiff * xDiff;
int yDiffSquared = yDiff * xDiff;
return (int)Math.Sqrt(xDiffSquared + yDiffSquared);
}
}
}
4 Answers
andren
28,558 PointsOne issue I notice is in the constructor of the Point
class:
public Point(int x, int y)
{
x = X;
y = Y;
}
You are setting x
(the parameter) equal to X
(the member variable), which is the opposite of what is intended. You are meant to set the member variable equal to the parameter. You also do the same thing for y
and Y
.
It's a typo that's easy to do and hard to notice, but it has a large effect. This constructor will lead to X
and Y
always being 0, since they are never actually assigned a value in the constructor.
This is likely what is causing your issue, so fixing that typo should fix the error.
Javier Gandia
Full Stack JavaScript Techdegree Student 9,153 PointsWow! Thank you! Simple mistake..
Mehmet Ali Ertörer
1,847 Pointsint yDiffSquared = yDiff * xDiff;
You need to multiply yDiff with yDiff. Not the xDiff. That's a pretty common mistake, and you don't need to worry about it
Adham Ali
Courses Plus Student 1,112 PointsYou got a logical error in the Point class constructor + you also got a logical error in the implementation of the DistanceTo method and that error is you say in the fourth written line of the method
int yDiffSquared = yDiff * xDiff;
which should be:
int yDiffSquared = yDiff * yDiff;