Prompt: This assignment provides an opportunity to work with defining classes an
ID: 3588453 • Letter: P
Question
Prompt: This assignment provides an opportunity to work with defining classes and creating objects (instantiating) from those classes. The exercise consists of source code that contains errors; therefore, it neither compiles nor runs correctly. It focuses on a console application, but the concepts translate across C# programming.
Consider the following C# console program that contains four programming errors. For the sake of simplicity and space, two classes are defined in the same file as opposed to the best practice of defining one class per file. ALSO PLEASE INDICATE CORRECTIONS MADE WITH COMMENTS:
namespace Classes
{
class Program
{
static void Main(string[] args)
{
Point origin = new Point();
Point bottomRight = another Point(1366, 768);
double distance = origin.DistanceTo(bottomRight);
Console.WriteLine("Distance is: {0}", distance);
Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
}
}
class Point
{
private int x, y;
private int objectCount = 0;
public void Point()
{
this.x = -1;
this.y = -1;
objectCount++;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
objectCount++;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
objectCount++;
}
private double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
return distance;
}
public static int ObjectCount()
{
return objectCount;
}
}
}
Explanation / Answer
using System.IO;
using System;
namespace Classes
{
class Program
{
static void Main(string[] args)
{
Point origin = new Point();
Point bottomRight = new Point(1366, 768);
double distance = origin.DistanceTo(bottomRight);
Console.WriteLine("Distance is: {0}", distance);
Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
}
}
class Point
{
private int x, y;
private static int objectCount = 0;
public Point()
{
this.x = -1;
this.y = -1;
objectCount++;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
objectCount++;
}
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
return distance;
}
public static int ObjectCount()
{
return objectCount;
}
}
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.