The exercise is as follows:
Create a class called Fraction that can be used to represent the ratio of two integers. Include appropriate constructors, properties, and methods. If the denominator becomes zero, throw and handle an exception. Create an application class to test the Fraction class.
The program runs. Will someone look over my code for this exercise?
Fraction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Part2
{
public class Fraction
{
private int numerator;
private int denominator;
/// <summary>
/// Initialize the fraction properties
/// </summary>
/// <param name="numerator">Upper number</param>
/// <param name="denominator">Lower number</param>
public Fraction(int numerator, int denominator)
{
this.Numerator = numerator;
this.Denominator = denominator;
}
/// <summary>
/// Access tot he numerator property
/// </summary>
public int Numerator
{
get { return this.numerator; }
set { this.numerator = value; }
}
/// <summary>
/// Access to the denominator property
/// </summary>
public int Denominator
{
get { return this.denominator; }
set
{
if (value == 0)
{
throw new Exception("0 denominator");
}
this.denominator = value;
}
}
/// <summary>
/// Return a string representation of a fraction
/// </summary>
/// <returns>Displayable attribute</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(this.Numerator + "/" + this.numerator);
sb.Append(" or ");
sb.Append(this.Numerator / this.Denominator);
return sb.ToString();
}
}
}
Application.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Part2
{
public class Application
{
/// <summary>
/// Entry point of the program
/// </summary>
public static void Main(string[] args)
{
// Create a fraction
Fraction f1 = new Fraction(1, 2);
Console.WriteLine(f1);
try
{
// Create another fraction
Fraction f2 = new Fraction(2, 0);
Console.WriteLine(f2);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}