using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyCal;
namespace CalcTestProject
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class DivTest
{
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void Test_ValidPositive()
{
//call method defined in the MyMath class
Assert.AreEqual(MyMath.Div("20","5"),"4.00");
Assert.AreEqual(MyMath.Div("25", "2"), "12.50");
Assert.AreEqual(MyMath.Div("20", "3"), "6.67");
Assert.AreEqual(MyMath.Div("2147483647", "2"), "1073741823.50");
}
[TestMethod]
public void Test_ValidNegative()
{
Assert.AreEqual(MyMath.Div("-40", "2"), "-20.00");
Assert.AreEqual(MyMath.Div("50", "-2"), "-25.00");
Assert.AreEqual(MyMath.Div("-4", "-2"), "2.00");
Assert.AreEqual(MyMath.Div("-2147483648", "-4"), "536870912.00");
}
[TestMethod]
public void Test_ValidZeroes()
{
Assert.AreEqual(MyMath.Div("0", "2"), "0.00");
Assert.AreEqual(MyMath.Div("2", "0"), "ERROR");
Assert.AreEqual(MyMath.Div("0", "0"), "ERROR");
}
[TestMethod]
[ExpectedException (typeof (FormatException))]
public void Test_CharFirstInput()
{
MyMath.Div("2aa", "4");
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Test_NotIntInput()
{
MyMath.Div("5.5", "2");
MyMath.Div("4", "2.2");
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Test_NotValidInput()
{
MyMath.Div("", "2");
MyMath.Div("22", "");
}
[TestMethod]
[ExpectedException(typeof(OverflowException))]
public void Test_RangeError()
{
MyMath.Div("2147483648", "2");
MyMath.Div("22", "-4147483467");
}
}
}
Showing posts with label PD2. Show all posts
Showing posts with label PD2. Show all posts
Monday, November 2, 2009
C# Unit Testing - Divide function div()
Labels:
C#,
formatexception,
overflowexception,
PD2,
Shanti,
unit testing
Tuesday, August 11, 2009
Homework - IComparable and IComparer - A step-by-step tutorial
1) Define your class City, as usual.
2) We need IComparable to our class to provide for a simple sorting capability
We need to provide a simple sorting capability to the code. We make use of the interface IComparable. To do that, we need to tell the class to implement the interface IComparable. Just add a column (:) and the interface name next to the class name.
3) IComparable Sorting capability - The CompareTo function
Now, we need to implement IComparable CompareTo function to provide the default sort order. We add the following code to our class:
4) Writing your tester class with an ArrayList
In this tutorial, I used the Form1 class as the tester class. The tester class will populate the Arraylist with values.
A listbox is made available on the form so that the cities are listed there.
Also, a button that shows "Simple Sort" is available and uses the ArrayList.Sort() method and does not require any additional implementation.
5) Sort list of cities first by state name, then by city name, without modifying the implementation of the City class
As Alan stated, you cannot redefine the CompareTo method. Let's stick to the requirement and define a CityComparer class that implements the Comparator<City> interface.
6) Call the method StateSort to sort by state in the Form1 class.
All done! Suggestions and comments are welcome.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CityCompare
{
public class City
{
//fields
private string name;
private string state;
//properties
public string Name
{
get { return name; }
set { name = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
//constructors
public City() { } //null constructor
public City(string _name, string _state)
{
this.name = _name;
this.state = _state;
}
//override toString method
public override string ToString()
{
return name + ", " + state;
}
}
}
2) We need IComparable to our class to provide for a simple sorting capability
We need to provide a simple sorting capability to the code. We make use of the interface IComparable. To do that, we need to tell the class to implement the interface IComparable. Just add a column (:) and the interface name next to the class name.
public class City : IComparable
3) IComparable Sorting capability - The CompareTo function
Now, we need to implement IComparable CompareTo function to provide the default sort order. We add the following code to our class:
//IComparable.CompareTo needs to be implemented
//to provide default sort order. Make it public
public int CompareTo(Object obj)
{
City c = (City)obj; //cast Object type to City object
return string.Compare(this.name, c.name);
}
4) Writing your tester class with an ArrayList
In this tutorial, I used the Form1 class as the tester class. The tester class will populate the Arraylist with values.
A listbox is made available on the form so that the cities are listed there.
Also, a button that shows "Simple Sort" is available and uses the ArrayList.Sort() method and does not require any additional implementation.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections; //add this line to use ArrayList
namespace CityCompare
{
public partial class Form1 : Form
{
//fields
private ArrayList cities = new ArrayList();
//properties
public ArrayList Cities
{
get { return cities; }
set { cities = value; }
}
//constructors
public Form1()
{
InitializeComponent();
}
//methods
//Populate the listbox
public void PopulateListBox()
{
//clear listbox
lisCitiesList.Items.Clear();
//Populate the listbox
foreach (Object item in cities)
{
lisCitiesList.Items.Add(item.ToString());
}
}
//Populate the ArrayList with cities and states
public void PopulateArrayList()
{
cities.Add(new City("Sydney", "New South Wales"));
cities.Add(new City("Albury", "New South Wales"));
cities.Add(new City("Armindale", "New South Wales"));
cities.Add(new City("Bathurst", "New South Wales"));
cities.Add(new City("Blue Mountains", "New South Wales"));
cities.Add(new City("Palmerston", "Northern Territory"));
cities.Add(new City("Darwin", "Northern Territory"));
cities.Add(new City("Melbourne", "Victoria"));
cities.Add(new City("Perth", "Western Australia"));
cities.Add(new City("Albany", "Western Australia"));
cities.Add(new City("Canning", "Western Australia"));
cities.Add(new City("Gosnells", "Western Australia"));
cities.Add(new City("Hobart", "Tasmania"));
cities.Add(new City("Hobart", "AnotherState"));
}
//events
private void Form1_Load(object sender, EventArgs e)
{
//Populate cities arraylist
PopulateArrayList();
//Populate listbox
PopulateListBox();
}
private void btnNormalSort_Click(object sender, EventArgs e)
{
cities.Sort();
PopulateListBox(); //refresh list
}
}
}
5) Sort list of cities first by state name, then by city name, without modifying the implementation of the City class
As Alan stated, you cannot redefine the CompareTo method. Let's stick to the requirement and define a CityComparer class that implements the Comparator<City> interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; //add this line to use interface IComparer
namespace CityCompare
{ //STEP 2
public class CityComparer: IComparer //we use this IComparer as it gives
//additional comparison mechanisms
{
//we need to implement the interface member Compare(obj,obj)
//from the interface IComparer
public int Compare(Object a, Object b) //make it public
{
City c1 = (City)a; //cast Object to City
City c2 = (City)b; //cast Object to City
return String.Compare(c1.State, c2.State); //State is a string,
//hence we use String.Compare
}
//StateSort method
//sorts the ArrayList elements by state
public static IComparer StateSort()
{
return (IComparer)new CityComparer();
}
}
}
6) Call the method StateSort to sort by state in the Form1 class.
private void btnCityComparer_Click(object sender, EventArgs e)
{
cities.Sort(CityComparer.StateSort()); //STEP 3
PopulateListBox(); //refresh list
}
All done! Suggestions and comments are welcome.
Wednesday, July 29, 2009
C# UML Class Diagram
Click to enlarge...
Shape Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShapeInheritance
{
public abstract class Shape //enforce that abstract MUST BE OVERRIDEN
{
//fields
protected double xPos; //'protect' modifier used because we want all
protected double yPos; //subclasses will generally inherit those fields
//constructors
public Shape(double _xPos, double _yPos)
{
this.xPos = _xPos;
this.yPos = _yPos;
}
//methods
public abstract double Area(); //enforce that Area HAS TO BE OVERRIDEN BY SUB-CLASSES
public override string ToString()
{
return "Position : (" + xPos.ToString() + ", " + yPos.ToString() + ")\n";
}
}
}
Circle class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShapeInheritance
{
public class Circle : Shape
{
//fields
private double radius;
//properties
public double Radius
{
get { return radius; }
set { radius = value; }
}
//constructors
public Circle() : base(0,0)
{
}
public Circle(double _xPos, double _yPos) : base(_xPos , _yPos)
{
}
public Circle(double _xPos, double _yPos, double _radius) : base(_xPos, _yPos)
{
this.radius = _radius;
}
//methods
public override double Area()
{
return Math.PI * Math.Pow(Radius, 2);
}
public override string ToString()
{
return base.ToString() + "\nradius : " + radius + "\nArea : " + Area().ToString("N2");
}
}
}
Cylinder class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShapeInheritance
{
public class Cylinder : Circle
{
//fields
private double height;
//properties
public double Height
{
get { return height; }
set { height = value; }
}
//constructors
public Cylinder() : base(0,0)
{
}
public Cylinder(double _xPos, double _yPos, double _radius, double _height) : base(_xPos, _yPos, _radius)
{
height = _height;
}
//methods
public override double Area()
{
return (2 * base.Area()) + (2 * Math.PI * Radius * height);
}
public double Volume()
{
return Math.PI * Math.Pow(Radius,2) * height;
}
public override string ToString()
{
return base.ToString() + "\nHeight : " + height + "\nVolume : " + Volume().ToString("N2");
}
}
}
Form coding:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ShapeInheritance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCircle_Click(object sender, EventArgs e)
{
Circle circle = new Circle(0, 0, 10);
lblText.Text = circle.ToString();
}
private void btnCylinder_Click(object sender, EventArgs e)
{
Cylinder cylinder = new Cylinder(0, 0, 10,10);
lblText.Text = cylinder.ToString();
}
}
}
Note:
1. Chain constructors are not used. Sub-constructors are calling the base constructor only.
2. Rectangle class not implemented.
Tuesday, July 28, 2009
Demonstrating Inheritance in C# - The Animal Class
The Animal class:
The Bat class:
The Hawk class:
The Monkey class:
The Snake class:
And finally, the GUI form sourcecode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceAnimals
{
public class Animal
{
//fields
private bool legs;
private bool wings;
//properties
public bool Legs
{
get { return legs; }
set { legs = value; }
}
public bool Wings
{
get { return wings; }
set { wings = value; }
}
//constructors
public Animal(bool _legs, bool _wings)
{
this.legs = _legs;
this.wings = _wings;
}
//methods
public virtual string eat()
{
return " unknown";
}
public virtual string hair()
{
return " unknown";
}
public virtual string sound()
{
return " unknown";
}
public virtual string movement()
{
return " unknown";
}
}
}
The Bat class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceAnimals
{
public class Bat : Animal
{
//fields
//properties
//constructors
public Bat():base(true,true)
{
}
public override string eat()
{
return "fruit and insects";
}
public override string hair()
{
return "feathers";
}
public override string movement()
{
return "unknown";
}
public override string sound()
{
return "unknown";
}
public string take_off()
{
return "launches from the tree";
}
public string land()
{
return "hangs on a rafter";
}
}
}
The Hawk class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceAnimals
{
public class Hawk : Animal
{
//fields
//properties
//constructors
public Hawk():base(true,true)
{
}
public override string eat()
{
return "small animals";
}
public override string hair()
{
return "feathers";
}
public override string sound()
{
return "Screeches";
}
public override string movement()
{
return "unknown";
}
public string take_off()
{
return "glides";
}
public string land()
{
return "perches on a tree top";
}
}
}
The Monkey class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceAnimals
{
public class Monkey : Animal
{
//fields
//properties
//constructors
public Monkey() : base(true, false)
{
}
public override string eat()
{
return "fruit";
}
public override string hair()
{
return "fur";
}
public override string sound()
{
return "Chatters";
}
public override string movement()
{
return "jumps";
}
}
}
The Snake class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritanceAnimals
{
public class Snake : Animal
{
//fields
//properties
//constructors
public Snake(): base(false,false)
{
}
public override string eat()
{
return "rats";
}
public override string hair()
{
return "none";
}
public override string sound()
{
return "Hisses";
}
public override string movement()
{
return "slithers";
}
}
}
And finally, the GUI form sourcecode:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InheritanceAnimals
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnShow_Click(object sender, EventArgs e)
{
Snake snake = new Snake();
Monkey monkey = new Monkey();
Bat bat = new Bat();
Hawk hawk = new Hawk();
string myresults = "";
myresults = "Snake (" + snake.Legs + " " + snake.Wings + ") eats " + snake.eat() + ", hair = " + snake.hair() + ", sound = " + snake.sound() + ", moves = " + snake.movement() +"\n\n";
myresults += "Monkey (" + monkey.Legs + " " + monkey.Wings + ") eats " + monkey.eat() + ", hair = " + monkey.hair() + ", sound = " + monkey.sound() + ", moves = " + monkey.movement() + "\n\n";
myresults += "Bat (" + bat.Legs + " " + bat.Wings + ") eats " + bat.eat() + ", hair = " + bat.hair() + ", sound = " + bat.sound() + ", moves = " + bat.movement() + ", takes off = " + bat.take_off() + ", lands = " + bat.land() + "\n\n";
myresults += "Hawk (" + hawk.Legs + " " + hawk.Wings + ") eats " + hawk.eat() + ", hair = " + hawk.hair() + ", sound = " + hawk.sound() + ", moves = " + hawk.movement() + ", takes off = " + hawk.take_off() + ", lands = " + hawk.land() + "\n\n";
lblResult.Text = myresults;
}
}
}
Wednesday, July 22, 2009
Understanding the concept of 1 to 1 relationship, and applying it to C#
Given the constraint that one object (Player) cannot exist without another object (Play Game), a one-to-one relationship representation in C# would mean that only one game per player, and without any game, we cannot have any player (makes perfect sense).
Tutorial to set up the One-to-One relationship
1) Set up the one-to-one relationship
Create your two independent forms (Form1 and Form2 by default) by adding them to your project in Visual Studio.
Now, you need to create a dependency between those two forms. I am using forms Game (Form1) and Player (Form2).
In Player (Form2) form where you would usually declare your fields,
Apply the same logic to the Form1 class, or the Game class.
2) Create the dependency that Form2 cannot exist without Form1.
We want the Play object to exist only if we have a Game.
Obviously, we cannot have a player if we do not have the game. To enforce this constraint, we make use of the constructor for the Form2, so that Form2 (or Game), will only be created if a Form1 object (Game) is not passed as an argument to the constructor.
So what did we exactly do? We said that if a Game exists, then the player also exists.
3) Show the second Form2 (Player) when the button on Form1 (Game) is clicked.
Run your code. On clicking the button from Form1 (Game), you will see the new form Player appear. You're on the right track. That's all we need to know to assign 1-to-1 dependency with constraints!
End of Tutorial
This was the first part of the question. The rest is very easy and will require the use of Random. I've included the full code of the application below.
The Game Class
The Play Class
I hope that helps!
Tutorial to set up the One-to-One relationship
1) Set up the one-to-one relationship
Create your two independent forms (Form1 and Form2 by default) by adding them to your project in Visual Studio.
Now, you need to create a dependency between those two forms. I am using forms Game (Form1) and Player (Form2).
In Player (Form2) form where you would usually declare your fields,
//fields
//create the dependency to Game Form
private Game myGameForm;
Apply the same logic to the Form1 class, or the Game class.
//fields
//create the dependency to Play Form
private Play myPlayForm;
2) Create the dependency that Form2 cannot exist without Form1.
We want the Play object to exist only if we have a Game.
//fields
//create the dependency to Play Form
private Play myPlayForm;
public Game()
{
myPlayForm = new Play(this);//create a Play form if the game exists
InitializeComponent();
}
Obviously, we cannot have a player if we do not have the game. To enforce this constraint, we make use of the constructor for the Form2, so that Form2 (or Game), will only be created if a Form1 object (Game) is not passed as an argument to the constructor.
//fields
//create the dependency to Game Form
private Game myGameForm;
public Play(Game gameform)
{
InitializeComponent();
myGameForm = gameform;//assign the object myGameForm to the argument gameform
}
So what did we exactly do? We said that if a Game exists, then the player also exists.
3) Show the second Form2 (Player) when the button on Form1 (Game) is clicked.
private void btnPlay_Click(object sender, EventArgs e)
{
myPlayForm.Show();
}
Run your code. On clicking the button from Form1 (Game), you will see the new form Player appear. You're on the right track. That's all we need to know to assign 1-to-1 dependency with constraints!
End of Tutorial
This was the first part of the question. The rest is very easy and will require the use of Random. I've included the full code of the application below.
The Game Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OneToOne
{
public partial class Game : Form
{
//fields
//create the dependency to Play Form
private Play myPlayForm;
//constructor
public Game()
{
myPlayForm = new Play(this);//create a Play form if the game exists
InitializeComponent();
}
//events
private void btnPlay_Click(object sender, EventArgs e)
{
myPlayForm.Show();
}
//methods
public void showValue(int maxval)
{
lblMax.Text = "Max Number is " + maxval.ToString()+ ".\n\nRestart game to play again";
}
}
}
The Play Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OneToOne
{
public partial class Play : Form
{
//fields
//create the dependency to Game Form
private Game myGameForm;
private int myNum = 0;
private int iCounter = 0;
//properties
public int MyNum
{
get { return myNum; }
set { myNum = value; }
}
public int ICounter
{
get { return iCounter; }
set { iCounter = value; }
}
//constructor
public Play(Game gameform)
{
InitializeComponent();
myGameForm = gameform; //assign the object myGameForm to the argument gameform
}
//events
private void btnClick_Click(object sender, EventArgs e)
{
showValue();
}
//methods
public void showValue()
{
Random myRan = new Random(); //create a myRan variable of type Random (Class)
int iRan = myRan.Next(100); //gets a random number from 0 - 100
iCounter++;
if (iCounter <= 3) //can click only 3 times
{
lblNum.Text = iRan.ToString(); //display random value on form
if (iRan >= myNum)
{
myNum = iRan;
}
}
else
{
MessageBox.Show("Cannot click more than 3 times. Turn has ended");
//prevent user from clicking more than 3 times
btnClick.Enabled = false;
//send the max value to Form1 or GameForm
myGameForm.showValue(myNum);
//hide this form
this.Hide();
//show the previous form
myGameForm.Show();
}
}
}
}
I hope that helps!
Subscribe to:
Posts (Atom)