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 Shanti. Show all posts
Showing posts with label Shanti. Show all posts
Monday, November 2, 2009
C# Unit Testing - Divide function div()
Labels:
C#,
formatexception,
overflowexception,
PD2,
Shanti,
unit testing
Monday, September 7, 2009
SQL Practice In class - My SQL solution
Q1
Q2
Q3
Q4
Q5
Q6
Q7
Q8
Q9
Q10
Q11
Q12
Q13
Q14
CREATE TABLE Employee
(
FirstName VARCHAR(30),
LastName VARCHAR(30),
email VARCHAR(30),
DOB DATETIME,
Phone VARCHAR(12)
)
INSERT INTO Employee
VALUES
('John', 'Smith', 'John.Smith@yahoo.com', '2/4/1968','626 222-222')
INSERT INTO Employee
(FirstName, LastName, email, DOB, Phone)
VALUES ('Steven', 'Goldfish', 'goldfish@fishhere.net', '4/4/1974', '323 455-4545')
INSERT INTO Employee
(FirstName, LastName, email, DOB, Phone)
VALUES ('Paula', 'Brown', 'pb@herowndomain.org', '5/24/1978', '416 323-3232')
INSERT INTO Employee
(FirstName, LastName, email, DOB, Phone)
VALUES ('James', 'Smith', 'jim@supergig.co.uk', '10/20/1980', '416 323-8888')
Q2
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
WHERE (LastName LIKE 'SMITH')
Q3
SELECT COUNT(*) AS Num_of_Emp_Like_SMITH
FROM Employee
WHERE (LastName LIKE 'SMITH')
Q4
SELECT LastName, COUNT(*) AS NumberOfEmp
FROM Employee
GROUP BY LastName
ORDER BY LastName DESC
Q5
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
WHERE (DOB >= '01/01/1970')
Q6
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
WHERE (Phone LIKE '416%')
Q7
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
WHERE (email LIKE '%.%@%.%')
Q8
UPDATE Employee
SET DOB = '05/10/1974'
WHERE (LastName = 'Goldfish') AND (FirstName = 'Steven')
Q9
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
ORDER BY DOB DESC
Q10
SELECT FirstName, LastName, email, DOB, Phone
FROM Employee
WHERE (FirstName LIKE '_____%')
Q11
ALTER TABLE Employee ADD Id INT IDENTITY
CONSTRAINT pk_ID PRIMARY KEY(Id)
Q12
SELECT FirstName, LastName, email, DOB, Phone, Id
FROM Employee
WHERE (DATEPART(m, DOB) = DATEPART(m, GETDATE()))
Q13
create table EmployeeHours
(
empFName Varchar(30),
empLName Varchar(30),
Date DATETIME,
Hours
insert into employeehours
VALUES
('John', 'Smith', '5/6/2004', 8)
insert into employeehours
VALUES
('John', 'Smith', '5/7/2004', 9)
insert into employeehours
VALUES
('Steven', 'Goldfish', '5/7/2004', 8)
insert into employeehours
VALUES
('James', 'Smith', '5/7/2004', 9)
insert into employeehours
VALUES
('John', 'Smith', '5/8/2004', 8)
insert into employeehours
VALUES
('James', 'Smith', '5/8/2004', 8)
Q13
Alter table EmployeeHours
add EmployeeID INT
CONSTRAINT fk_ID Foreign Key (EmployeeID) References Employee(id)
Q14
CREATE PROCEDURE UpdateEmpId
AS
UPDATE EmployeeHours
SET EmployeeId =
(SELECT Id
FROM Employee
WHERE (EmployeeHours.EmpFName = FirstName) AND (EmployeeHours.EmpLName = LastName))
Thursday, September 3, 2009
PART 1 & 2 - SQL User Defined Functions - Homework solutions
Question 1
Create a function called fnGetTimeOnly to return the time part (hh:mm) of a DateTime value
Create a function called fnGetDateOnly to return the date part (dd/mm/yyyy) of a DateTime value
Create a stored procedure called OrderDateTimeSpecific to return all order dates by splitting the date part and the time part into different columns. Use the functions created above in the stored procedure.
Question 2
Create a function called fnContactInfo that returns a table containing all employees full name and their contact number
Create a query to return all values from the fnContactInfo function
Question 3
Create a function called fnLastDay to get the last day in a month of a given date.
Create a query to return all employees and their pay day last month, this month, and next month. The pay day is always the last day of the month.
Question 4
Create a function called fnRoundCurrency to format the currency value into the correct monetary format. For e.g. 39.07 should be rounded to 39.10.
Modify the stored procedure created last week and call this function to format the new price of the first ten products into the right format.
PART II
Create a table called Books in Northwind database containing BookID, ISBN, Publisher, Author, Year, Country, Category, Description.
Question 1: FUNCTIONS TO CHECK CONSTRAINTS IN A TABLE DEFINITION
Create a function called fnValidISBN to check the value entered into ISBN field in the Books table. The following requirements are to check for valid ISBN:
ISBN numbers can contain 10 or 13 digits number.
Assuming that the company only accepts English-language publisher books, make sure that the ISBN follows the systematic pattern.
To check if the numbers entered are valid or not, use the formula and pattern in this webpage: http://en.wikipedia.org/wiki/International_Standard_Book_Number
Create a function called fnGetTimeOnly to return the time part (hh:mm) of a DateTime value
ALTER FUNCTION dbo.fnGetTimeOnly(@datefield DATETIME)
RETURNS varchar(5)
AS
BEGIN
RETURN CONVERT(VARCHAR(2),
DATEPART(hh,@datefield)) + ':' + CONVERT(VARCHAR(2),DATEPART(mi,@datefield))
END
----------------------------------------------------
SELECT dbo.fnGetTimeOnly(GETDATE()) AS Expr1
Create a function called fnGetDateOnly to return the date part (dd/mm/yyyy) of a DateTime value
ALTER FUNCTION dbo.fnGetDateOnly
(@datefield DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
RETURN CONVERT(VARCHAR(2),DATEPART(dd,@datefield))+ '/' +
CONVERT(VARCHAR(2),DATEPART(mm,@datefield))+ '/' +
CONVERT(VARCHAR(4),DATEPART(yyyy,@datefield))
END
---------------------------------------------------------
SELECT dbo.fnGetDateOnly(NOW()) AS Expr1
Create a stored procedure called OrderDateTimeSpecific to return all order dates by splitting the date part and the time part into different columns. Use the functions created above in the stored procedure.
ALTER PROCEDURE dbo.OrderDateTimeSpecific
AS
SELECT dbo.fnGetDateOnly(OrderDate) AS OrderDate,
dbo.fnGetTimeOnly(OrderDate) AS OrderTime
FROM Orders
RETURN
Question 2
Create a function called fnContactInfo that returns a table containing all employees full name and their contact number
ALTER FUNCTION dbo.fnContactInfo()
RETURNS @contactInfoTable TABLE (fullname varchar(30), contactnumber varchar(24))
AS
BEGIN
INSERT INTO @contactInfoTable
SELECT FirstName + ' ' + LastName, HomePhone FROM Employees
RETURN
END
Create a query to return all values from the fnContactInfo function
SELECT fullname, contactnumber
FROM dbo.fnContactInfo() AS fnContactInfo_1
Question 3
Create a function called fnLastDay to get the last day in a month of a given date.
ALTER FUNCTION dbo.fnLastDay(@givendate DATETIME)
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE @dayindex INT
DECLARE @lastday VARCHAR(30)
DECLARE @lastdate DATETIME
SET @lastdate = DATEADD(day, - 1, DATEADD(month, DATEDIFF(month, 0, @givendate) + 1, 0))
SET @dayindex = CONVERT(INT,DATEPART(weekday,@lastdate))
SELECT @lastday =
CASE @dayindex
WHEN 1
THEN 'Family Day Sunday'
WHEN 2
THEN 'Back to work Day Monday'
WHEN 3
THEN 'Movie night Tuesday'
WHEN 4
THEN 'Borrow money day Wednesday'
WHEN 5
THEN 'Shopping spree Thursday'
WHEN 6
THEN 'Binge drinking night Friday'
WHEN 7
THEN 'Activities day Saturday'
END
RETURN @lastday
END
Create a query to return all employees and their pay day last month, this month, and next month. The pay day is always the last day of the month.
SELECT LastName, FirstName,
dbo.fnLastDay(DATEADD(month, - 1, GETDATE())) AS PreviousMonthPayDay,
dbo.fnLastDay(GETDATE()) AS ThisMonthPayDay,
dbo.fnLastDay(DATEADD(month, 1, GETDATE())) AS NextMonthPayDay
FROM Employees
Question 4
Create a function called fnRoundCurrency to format the currency value into the correct monetary format. For e.g. 39.07 should be rounded to 39.10.
ALTER FUNCTION dbo.fnRoundCurrency(@currency MONEY)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN CAST ((ROUND((@currency * 2),1) /10) *5 AS DECIMAL(10,2))
END
Modify the stored procedure created last week and call this function to format the new price of the first ten products into the right format.
ALTER PROCEDURE dbo.spShowCorrectPrice
AS
SELECT TOP 10 *,dbo.fnRoundCurrency(UnitPrice) as RoundedPrice FROM Products
RETURN
PART II
Create a table called Books in Northwind database containing BookID, ISBN, Publisher, Author, Year, Country, Category, Description.
CREATE TABLE Books
(
BookID INT,
ISBN VARCHAR(13),
Publisher VARCHAR(30),
Author VARCHAR(30),
Year INT,
Country VARCHAR(20),
Category VARCHAR(30),
Description VARCHAR(30),
CONSTRAINT pk_BookID PRIMARY KEY (BookID)
)
Question 1: FUNCTIONS TO CHECK CONSTRAINTS IN A TABLE DEFINITION
Create a function called fnValidISBN to check the value entered into ISBN field in the Books table. The following requirements are to check for valid ISBN:
ISBN numbers can contain 10 or 13 digits number.
Assuming that the company only accepts English-language publisher books, make sure that the ISBN follows the systematic pattern.
To check if the numbers entered are valid or not, use the formula and pattern in this webpage: http://en.wikipedia.org/wiki/International_Standard_Book_Number
ALTER FUNCTION dbo.fnValidISBN
(@isbn VARCHAR(13))
RETURNS INT
AS
BEGIN
DECLARE @result INT
DECLARE @isbn_ten INT
DECLARE @isbn_thirteen INT
DECLARE @isbn_sum INT
DECLARE @startpos INT
DECLARE @isbnlen INT
SET @isbn_ten = 9
SET @isbn_thirteen = 12
SET @isbn_sum = 0
SET @startpos = 1
SET @isbnlen = LEN(@isbn)
IF (@isbnlen = @isbn_ten)
BEGIN
WHILE (@startpos<= @isbn_ten+1)
BEGIN
SET @isbn_sum = @isbn_sum + (@isbn_ten * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END
IF (11-@isbn_sum%11) = SUBSTRING(@isbn,10,1)
SET @result = 0 --Success
ELSE
SET @result= 1 --Failure
END
ELSE IF (@isbnlen = @isbn_thirteen+1)
BEGIN
WHILE (@startpos <= @isbn_thirteen)
BEGIN
IF @startpos % 2 <> 0
BEGIN
SET @isbn_sum = @isbn_sum + (1 * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END
ELSE
BEGIN
SET @isbn_sum = @isbn_sum + (3 * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END
END
IF (10 - @isbn_sum % 10) = SUBSTRING(@isbn,13,1)
SET @result = 0 --Success
ELSE
SET @result= 1 --Failure
END
ELSE SET @result = 1
RETURN @result
END
---------------------------------------------
SELECT dbo.fnValidISBN(9780306406156) AS Expr1
Friday, August 28, 2009
WHILE LOOP Stored Procedure - Class example
Add 5 new customers and date
Calculate to new salary average
ALTER PROCEDURE spAddCustomerIDtoOrdersFiveTimes
@CustID NCHAR(5)
AS
DECLARE @counter INT
SET @counter = 0
WHILE @counter < 5
BEGIN
INSERT INTO Orders (CustomerID, OrderDate)
VALUES (@CustID, DATEADD(day,@counter,GETDATE()))
SET @counter = @counter +1
END
RETURN
Calculate to new salary average
ALTER PROCEDURE spIncreaseSalUntilTargetReached
@target money
AS
DECLARE @avg MONEY
DECLARE @count INT
SET @count = 0
SELECT @avg = AVG(SAL) FROM EMP
WHILE @avg < @target
BEGIN
UPDATE EMP
SET SAL = SAL + 50
SELECT @avg = AVG(SAL) FROM EMP
SET @count = @count + 1
END
PRINT 'No of records updated: ' + CAST(@count AS VARCHAR(20))
PRINT 'Calculated AVG: ' + CAST(@avg AS VARCHAR(20))
RETURN
Monday, August 24, 2009
SQL Northwind DB - Stored Procedures
1. Create a stored procedure to search employees by the first few letters in their last name.
2. Create a stored procedure to create a new product and a new category by passing the CategoryName, ProductName, and the status (Discontinued) is False.
3. Create a stored procedure to show the stock level of every product in the Products table. For unit stock under 20, the stock level is low. Unit stock above 100, the stock level is high. For the rest, the stock level is medium.
4. Create a stored procedure to display the territory status for each territory in Territories table. Territories id that starts with 9 is considered as big cities. Territories id starts with 0 or 1 is considered as small cities. Territories id starts with 2 to 6 is considered as other cities. Territories id starts with 7 or 8 is considered as popular cities.
5. Create a stored procedure to find the new price of the first 10 products in Products table. The new price will be calculated based on the amount of percentage inputted into the procedure. The output should show the old and the new prices.
CREATE PROCEDURE dbo.spSearchEmployeebyLName
@LName nvarchar(20)
AS
SET @LName = @LName + '%'
SELECT * FROM Employees
WHERE LastName LIKE @LName
RETURN
2. Create a stored procedure to create a new product and a new category by passing the CategoryName, ProductName, and the status (Discontinued) is False.
CREATE PROCEDURE spCreateNewProduct
@CategoryName nvarchar(15),
@ProductName nvarchar(40),
@Status bit = 'False'
AS
DECLARE @CatID INT;
INSERT INTO Categories (CategoryName)
VALUES ( @CategoryName )
SET @CatID=@@IDENTITY
INSERT INTO Products (ProductName, CategoryID, Discontinued)
VALUES (@ProductName, @CatID, @Status)
RETURN
3. Create a stored procedure to show the stock level of every product in the Products table. For unit stock under 20, the stock level is low. Unit stock above 100, the stock level is high. For the rest, the stock level is medium.
CREATE PROCEDURE spShowStockLevel
AS
SELECT ProductID, ProductName, UnitsInStock,
CASE
WHEN UnitsInStock <20
THEN 'LOW'
WHEN UnitsInStock >100
THEN 'HIGH'
ELSE
'MEDIUM'
END
AS StockLevel
FROM Products
RETURN
4. Create a stored procedure to display the territory status for each territory in Territories table. Territories id that starts with 9 is considered as big cities. Territories id starts with 0 or 1 is considered as small cities. Territories id starts with 2 to 6 is considered as other cities. Territories id starts with 7 or 8 is considered as popular cities.
CREATE PROCEDURE spShowTerritoryStatus
AS
SELECT TerritoryID, TerritoryDescription,
CASE
WHEN TerritoryID LIKE '9%'
THEN 'big cities'
WHEN TerritoryID LIKE '[0-1]%'
THEN 'small cities'
WHEN TerritoryID LIKE '[2-6]%'
THEN 'other cities'
WHEN TerritoryID LIKE '[7-8]%'
THEN 'big cities'
END
AS TerritoryStatus
FROM Territories
RETURN
5. Create a stored procedure to find the new price of the first 10 products in Products table. The new price will be calculated based on the amount of percentage inputted into the procedure. The output should show the old and the new prices.
CREATE PROCEDURE spFindNewPrice
@Percentage DECIMAL
AS
SELECT ProductID, ProductName, UnitPrice,
NewUnitPrice = ROUND(( ( (@Percentage/100) +1 ) * UnitPrice ),2)
FROM Products
RETURN
Monday, June 1, 2009
Car Object, Using array of 10 objects
The Enum is as follows:
The Car Class is as follows:
The Form is as follows:
public enum Built
{
Hatch=0,
Sedan=1,
Wagon=2,
Coupe=3
}
The Car Class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyCarProject
{
public class MyCar
{
//fields
#region fields
private string model;
private int year;
private string color;
private Built built;
#endregion
//properties
#region properties
public string Model
{
get { return model; }
set { model = value; }
}
public int Year
{
get { return year; }
set { year = value; }
}
public string Color
{
get { return color; }
set { color = value; }
}
public Built Built
{
get { return built; }
set { built = value; }
}
#endregion
//constructors
#region constructors
public MyCar()
{
}
public MyCar(string _model, int _year, string _color, Built _built)
{
this.model = _model;
this.year = _year;
this.color = _color;
this.built = _built;
}
#endregion
//methods
#region methods
public override string ToString()
{
string msg = "";
msg = "Model : " + this.model + "\n" +
"Year : " + this.year + "\n" +
"Color : " + this.color + "\n" +
"Built : " + this.built;
return msg;
}
#endregion
}
}
The Form is as follows:
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 MyCarProject
{
public partial class Form1 : Form
{
//fields
#region fields
private MyCar[] carArray = new MyCar[10];
#endregion
//properties
#region properties
public MyCar[] CarArray
{
get { return carArray; }
set { carArray = value; }
}
#endregion
//constructors
#region constructors
public Form1()
{
InitializeComponent();
}
#endregion
//methods-events
#region methods-events
private void Form1_Load(object sender, EventArgs e)
{
//add Built items into combobox
cmbBuilt.Items.Add(Built.Coupe);
cmbBuilt.Items.Add(Built.Hatch);
cmbBuilt.Items.Add(Built.Sedan);
cmbBuilt.Items.Add(Built.Wagon);
}
public bool addCar(MyCar obj)
{
for (int i = 0; i < carArray.Length; i++)
{
if (carArray[i] == null)
{
carArray[i] = obj;
return true;
}
}
return false;
}
public MyCar searchByModel(string _model)
{
for (int i = 0; i < carArray.Length; i++)
{
if (_model == carArray[i].Model)
{
return carArray[i];
}
}
return null;
}
public bool updateCar(string _model, MyCar obj)
{
for (int i = 0; i < carArray.Length; i++)
{
if ((_model == carArray[i].Model) && (carArray[i] != null))
{
carArray[i] = obj; //update car object
return true;
}
}
return false;
}
public bool deleteCar(string _model)
{
for (int i = 0; i < carArray.Length; i++)
{
if ((carArray[i].Model == _model) && (carArray[i] != null))
{
carArray[i] = null;
return true;
}
}
return false;
}
public string displayAllCars()
{
string msg = "";
for (int i = 0; i < carArray.Length; i++)
{
if (carArray[i] != null)
{
msg += carArray[i].ToString() + "\n\n";
}
}
return msg;
}
private void btnAdd_Click(object sender, EventArgs e)
{
//read gui
MyCar carObj = new MyCar();
try
{
carObj.Model = txtModel.Text;
carObj.Year = int.Parse(txtYear.Text);
carObj.Color = txtColor.Text;
carObj.Built = (Built)cmbBuilt.SelectedItem;
bool boolAdd = addCar(carObj);
if (boolAdd == true)
{
MessageBox.Show("Car successfully added.");
}
else
{
MessageBox.Show("Car NOT added. Car Array might be full.");
}
}
catch //parsing error
{
MessageBox.Show("Please fill all appropriate fields with correct values");
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
MyCar obj = searchByModel(txtModel.Text);
if (obj != null) //car found
{
txtYear.Text = "" + obj.Year;
txtColor.Text = "" + obj.Color;
cmbBuilt.SelectedItem = obj.Built;
MessageBox.Show("Car found");
}
else
{
MessageBox.Show("Car not found");
}
}
catch
{
MessageBox.Show("Please enter a valid model name");
txtModel.Focus();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
MyCar car = new MyCar();
car.Model = txtModel.Text;
car.Year = int.Parse(txtYear.Text);
car.Color = txtColor.Text;
car.Built = (Built)cmbBuilt.SelectedItem;
bool boolUpdate = updateCar(car.Model, car);
if (boolUpdate == true)
{
MessageBox.Show("Update Completed");
}
else
{
MessageBox.Show("Update Failed");
}
}
catch
{
MessageBox.Show("Could not perform update");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
bool boolDelete = deleteCar(txtModel.Text);
if (boolDelete == true)
MessageBox.Show("Delete Completed");
else
MessageBox.Show("Delete Failed");
}
catch
{
MessageBox.Show("Could not perform delete");
}
}
private void btnDisplayAll_Click(object sender, EventArgs e)
{
string carList = displayAllCars();
if (carList != "")
{
MessageBox.Show(carList);
}
else
{
MessageBox.Show("No cars available to display");
}
}
#endregion
}
}
Sunday, May 24, 2009
Shanti C# - Card Class - Homework Part 1
The Card class question, as a continuation from Misa's previous post (well, it's more like the prequel, cos this is part 1 :) ).
This part is the form implementation:
namespace SimpleCard
{
public class SimpleCard
{
//fields
private int cardValue; //instance variable
public const int ACE = 1;
public const int TWO = 2;
public const int THREE = 3;
public const int FOUR = 4;
public const int FIVE = 5;
public const int SIX = 6;
public const int SEVEN = 7;
public const int EIGHT = 8;
public const int NINE = 9;
public const int TEN = 10;
public const int JACK = 11;
public const int QUEEN = 12;
public const int KING = 13;
public static int CardInASet = 13;
//properties
//cardValue
public int CardValue
{
get { return cardValue; }
set { cardValue = value; }
}
//constructors
public SimpleCard() //null constructor
{
cardValue = 1;
}
public SimpleCard(int _cardValue)
{
cardValue = _cardValue;
}
public SimpleCard(string _cardValueName)
{
switch (_cardValueName)
{
case "ACE":
cardValue = 1;
break;
case "TWO":
cardValue = 2;
break;
case "THREE":
cardValue = 3;
break;
case "FOUR":
cardValue = 4;
break;
case "FIVE":
cardValue = 5;
break;
case "SIX":
cardValue = 6;
break;
case "SEVEN":
cardValue = 7;
break;
case "EIGHT":
cardValue = 8;
break;
case "NINE":
cardValue = 9;
break;
case "TEN":
cardValue = 10;
break;
case "JACK":
cardValue = 11;
break;
case "QUEEN":
cardValue = 12;
break;
case "KING":
cardValue = 13;
break;
}
}
//methods
//instance method
public string getCardName()
{
string cardName = "";
switch (cardValue)
{
case 1:
cardName = "ACE";
break;
case 2:
cardName = "TWO";
break;
case 3:
cardName = "THREE";
break;
case 4:
cardName = "FOUR";
break;
case 5:
cardName = "FIVE";
break;
case 6:
cardName = "SIX";
break;
case 7:
cardName = "SEVEN";
break;
case 8:
cardName = "EIGHT";
break;
case 9:
cardName = "NINE";
break;
case 10:
cardName = "TEN";
break;
case 11:
cardName = "JACK";
break;
case 12:
cardName = "QUEEN";
break;
case 13:
cardName = "KING";
break;
}//end switch
return cardName;
}
public string getInfo()
{
string cardInfo = "";
switch (cardValue)
{
case 1:
cardInfo = "ACE " + cardValue.ToString();
break;
case 2:
cardInfo = "TWO " + cardValue.ToString();
break;
case 3:
cardInfo = "THREE " + cardValue.ToString();
break;
case 4:
cardInfo = "FOUR " + cardValue.ToString();
break;
case 5:
cardInfo = "FIVE " + cardValue.ToString();
break;
case 6:
cardInfo = "SIX " + cardValue.ToString();
break;
case 7:
cardInfo = "SEVEN " + cardValue.ToString();
break;
case 8:
cardInfo = "EIGHT " + cardValue.ToString();
break;
case 9:
cardInfo = "NINE " + cardValue.ToString();
break;
case 10:
cardInfo = "TEN " + cardValue.ToString();
break;
case 11:
cardInfo = "JACK " + cardValue.ToString();
break;
case 12:
cardInfo = "QUEEN " + cardValue.ToString();
break;
case 13:
cardInfo = "KING " + cardValue.ToString();
break;
}//end switch
return cardInfo;
}
}
}
This part is the form implementation:
namespace SimpleCard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtCard.Text != "")
{
try //for integer
{
int iCardVal = int.Parse(txtCard.Text.ToString().Trim());
if (iCardVal > 0 && iCardVal <= 13)
{
SimpleCard myCard = new SimpleCard(iCardVal);
MessageBox.Show("Card is " + myCard.getInfo());
}
else
MessageBox.Show("Card does not exist");
}
catch //for string
{
string myCardName = txtCard.Text.ToString().Trim().ToUpper();
SimpleCard myCard = new SimpleCard(myCardName);
MessageBox.Show("Card is " + myCard.getInfo());
}
}
else
{
MessageBox.Show("Enter a value");
txtCard.Focus();
}
}
private void btnDisplayAllCards_Click(object sender, EventArgs e)
{
string myCardNames = "";
for (int i = 1; i <= 13; i++)
{
SimpleCard card = new SimpleCard(i);
myCardNames += " " + card.getCardName();
}
MessageBox.Show(myCardNames);
}
}
}
Friday, May 22, 2009
Monday, May 11, 2009
Shanti C# Homework - Time Class
For all those students who didn't attend class today :)
OOP – Creating a Class Exercise 2
Create the following class and its fields, properties, constructors, and methods. The Time class is used to
represent duration of time in hours, minutes, and seconds.
STEP 1: Create the Time class
STEP 2: Define the fields
STEP 3: Define the properties
STEP 4: Define the constructors (null and with arguments)
STEP 5: Time class should have at least the following methods:
A method to show the information in the following format: hh:mm:ss
A method to add seconds into the Time. For example: 01:02:03 plus 12 seconds is equal to
01:02:15.
A method to find the sum of two Time values. For example: 01:02:03 plus 11:22:33 is equal to
12:24:36.
A method to check if two Time values are equal. For example: 01:02:03 and 01:02:03 are equal.
STEP 6: Create the user interface (form) where a user can input the hours, minutes, and
seconds, display the information in presentable format (hh:mm:ss), find the sum of two
Time values, add seconds into the Time, and compare two Time values.
STEP 7: Consider the following scenario and modify the specification of Time class if
necessary:
Can the hours, minutes, and seconds be negative values?
Are there maximum and minimum values for hours, minutes, and seconds?
How many different ways are there to create a Time object? Can the Time object be
created by specifying only the hours and/or the minutes?
What happens when you add some seconds into a Time value and the seconds part
of the Time value exceeds 59 seconds? For example: Should the result of this
operation (01:00:59 plus 2 seconds) be 01:00:61 or 01:01:01?
What happens when you add two Time values and the minutes and seconds part of
the Time value exceeds 59? For example: Should the result of this operation
(01:50:50 plus 02:20:30) be 03:70:80 or 04:11:20?
OOP – Creating a Class Exercise 2
Create the following class and its fields, properties, constructors, and methods. The Time class is used to
represent duration of time in hours, minutes, and seconds.
STEP 1: Create the Time class
STEP 2: Define the fields
STEP 3: Define the properties
STEP 4: Define the constructors (null and with arguments)
STEP 5: Time class should have at least the following methods:
A method to show the information in the following format: hh:mm:ss
A method to add seconds into the Time. For example: 01:02:03 plus 12 seconds is equal to
01:02:15.
A method to find the sum of two Time values. For example: 01:02:03 plus 11:22:33 is equal to
12:24:36.
A method to check if two Time values are equal. For example: 01:02:03 and 01:02:03 are equal.
STEP 6: Create the user interface (form) where a user can input the hours, minutes, and
seconds, display the information in presentable format (hh:mm:ss), find the sum of two
Time values, add seconds into the Time, and compare two Time values.
STEP 7: Consider the following scenario and modify the specification of Time class if
necessary:
Can the hours, minutes, and seconds be negative values?
Are there maximum and minimum values for hours, minutes, and seconds?
How many different ways are there to create a Time object? Can the Time object be
created by specifying only the hours and/or the minutes?
What happens when you add some seconds into a Time value and the seconds part
of the Time value exceeds 59 seconds? For example: Should the result of this
operation (01:00:59 plus 2 seconds) be 01:00:61 or 01:01:01?
What happens when you add two Time values and the minutes and seconds part of
the Time value exceeds 59? For example: Should the result of this operation
(01:50:50 plus 02:20:30) be 03:70:80 or 04:11:20?
Sunday, May 10, 2009
Shanti C# - Rectangle and Point Class - Complete
Rectangle Class
Point Class (Used to override the ToString() function) - optional
Form Coding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RectangleClass
{
public class Rectangle
{
//fields
private int length = 0;
private int width = 0;
private Point corner = new Point(0,0);
//properties
public int Length
{
get { return length; }
set { length=value; }
}
public int Width
{
get { return width; }
set { width = value; }
}
public Point Corner
{
get { return corner; }
set { corner = value; }
}
//constructors
public Rectangle()
{
}
public Rectangle(int _length, int _width, Point _corner)
{
length = _length;
width = _width;
corner = _corner;
}
//methods
public int getArea()
{
return length * width;
}
public int getPerimeter()
{
return (length + width) * 2;
}
public void increaseLength(int _lengthIncrease)
{
length = length + _lengthIncrease;
}
public void increaseWidth(int _widthIncrease)
{
width = width + _widthIncrease;
}
public string getCenter()
{
corner.setPoint(length / 2, width / 2);
return corner.ToString();
}
public string getTopRight()
{
corner.setPoint(length, 0);
return corner.ToString();
}
public string getBottomLeft()
{
corner.setPoint(0, width);
return corner.ToString();
}
public string getBottomRight()
{
corner.setPoint(length, width);
return corner.ToString();
}
public string getAllPoints()
{
string sAllPoints = "";
sAllPoints = "Center = " + getCenter() + "\n" +
"Top Right = " + getTopRight() + "\n" +
"Bottom Left = " + getBottomLeft() + "\n" +
"Bottom Right = " + getBottomRight();
return sAllPoints;
}
}
}
Point Class (Used to override the ToString() function) - optional
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RectangleClass
{
public class Point
{
//fields
private int x, y;
// Default constructor:
public Point()
{
x = 0;
y = 0;
}
// A constructor with two arguments:
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
// Override the ToString method:
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}
public void setPoint(int _x, int _y)
{
this.x = _x;
this.y = _y;
}
}
}
Form Coding
Rectangle myRec1 = new Rectangle(0, 0, new Point());
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnGetLength_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Length is " + myRec1.Length);
}
private void btnGetWidth_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Width is " + myRec1.Width);
}
private void btnArea_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Area is " + myRec1.getArea());
}
private void btnPerimeter_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Area is " + myRec1.getPerimeter());
}
private void CheckFields()
{
myRec1.Length = 0;
myRec1.Width = 0;
if (txtLengthInc.Text != "")
myRec1.increaseLength(int.Parse(txtLengthInc.Text));
if (txtWidthInc.Text != "")
myRec1.increaseWidth(int.Parse(txtWidthInc.Text));
if (txtLength.Text != "")
myRec1.Length = myRec1.Length + int.Parse(txtLength.Text);
if (txtWidth.Text != "")
myRec1.Width = myRec1.Width + int.Parse(txtWidth.Text);
}
private void btnCenter_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show ("Center : " + myRec1.getCenter());
}
private void btnTopRight_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Top Right : " + myRec1.getTopRight());
}
private void btnBottomLeft_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Bottom Left : " + myRec1.getBottomLeft ());
}
private void btnButtonRight_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Bottom Right : " + myRec1.getBottomRight());
}
private void btnAllPoints_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show(myRec1.getAllPoints());
}
Wednesday, May 6, 2009
Shanti's Web Classwork
Question 1 - Countdown
Question 2 - Multiplication
Question 3 - Online Reservation
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script type="text/javascript">
var num = prompt("Enter number > 0", "0");
while ((num <=0) || (isNaN(num)==true))
{
var num = prompt("Enter number > 0", "0");
}
for (var i=0; i<num; i++)
{
alert("Starting in " + (num-i));
}
alert ("Roll Film!");
</script>
</body>
</html>
Question 2 - Multiplication
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script type="text/javascript">
document.write("<table><tr><td colspan=10><h1>Multiplication Table</h1></td></tr>");
for(var i = 1; i <= 10; i++)
{
document.write("<tr>");
for (var j = 1 ; j <= 10; j++)
{
document.write("<td>" + i + " * " + j + " = " + (i * j) + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
</html>
Question 3 - Online Reservation
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script type="text/javascript">
function assignSeat()
{
for (var i = 1; i <= 5; i ++)
{
if (document.getElementById(i).title == "a")
{
document.getElementById(i).src= "seat_select.png";
if (confirm("Seat " + i + " is available. Accept? "))
{
document.getElementById(i).src = "seat_unavail.png";
document.getElementById(i).title = "u";
break;
}
else
{
}
document.getElementById(i).src= "seat_avail.png";
}
}
}
</script>
<img src="seat_avail.png" alt = "1" id="1" title = "a" />
<img src="seat_avail.png" alt = "2" id="2" title = "a" />
<img src="seat_avail.png" alt = "3" id="3" title = "a" />
<img src="seat_avail.png" alt = "4" id="4" title = "a" />
<img src="seat_avail.png" alt = "5" id="5" title = "a" />
<br />
<input type="button" value="Reserve Seat" onclick="assignSeat()" />
</body>
</html>
Monday, May 4, 2009
Shanti's Classwork - Rectangle Class
Code without the implementation for the Point object.
Class Definition for Rectangle:
UI Form
Class Definition for Rectangle:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RectangleClass
{
class Rectangle
{
//fields
private int length = 0;
private int width = 0;
//properties
public int Length
{
get { return length; }
set { length=value; }
}
public int Width
{
get { return width; }
set { width = value; }
}
//constructors
public Rectangle()
{
}
public Rectangle(int _length, int _width)
{
length = _length;
width = _width;
}
//methods
public int getArea()
{
return length * width;
}
public int getPerimeter()
{
return (length + width) * 2;
}
public void increaseLength(int _lengthIncrease)
{
length = length + _lengthIncrease;
}
public void increaseWidth(int _widthIncrease)
{
width = width + _widthIncrease;
}
}
}
UI Form
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 RectangleClass
{
public partial class Form1 : Form
{
Rectangle myRec1 = new Rectangle(0, 0);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnGetLength_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Length is " + myRec1.Length);
}
private void btnGetWidth_Click(object sender, EventArgs e)
{
MessageBox.Show("Width is " + myRec1.Width);
}
private void btnArea_Click(object sender, EventArgs e)
{
MessageBox.Show("Area is " + myRec1.getArea());
}
private void btnPerimeter_Click(object sender, EventArgs e)
{
MessageBox.Show("Area is " + myRec1.getPerimeter());
}
private void CheckFields()
{
if (txtLengthInc.Text != "")
myRec1.increaseLength(int.Parse(txtLengthInc.Text));
if (txtWidthInc.Text != "")
myRec1.increaseWidth(int.Parse(txtWidthInc.Text));
if (txtLength.Text != "")
myRec1.Length = myRec1.Length + int.Parse(txtLength.Text);
if (txtWidth.Text != "")
myRec1.Width = myRec1.Width + int.Parse(txtWidth.Text);
}
}
}
Wednesday, April 29, 2009
Stick Figure Storyboard with Javascript
Assume that all pictures are in the same folder with the HTML page...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Story Board</title>
<script type="text/javascript">
var scene = 0;
function changeImg(num)
{
if (scene==0)
{
alert("Your journey begins at a fork in the road.");
scene=1;
}
else if (scene==1)
{
if(num==1)
{
alert("You have arrived at a cute little house in the woods.");
scene=2;
}
else if (num ==2)
{
alert("You are standing on the bridge overlooking a peaceful stream.");
scene=3;
}
}
else if (scene==2)
{
if(num==1)
{
alert("Peeking through the window, you see a witch inside the house.");
scene=4;
}
else if (num ==2)
{
alert("Sorry, a witch lives in the house and you just became part of her stew.");
scene=5;
}
}
else if (scene==4)
{
if(num==1)
{
scene=8;
}
else if (num ==2)
{
alert("Sorry, a witch lives in the house and you just became part of her stew.");
scene=5;
}
}
else if (scene==5)
{
scene=0;
}
else if (scene==3)
{
if(num==1)
{
alert("Sorry, a troll lives on the other side of the bridge and you just became his lunch.");
scene=6;
}
else if (num ==2)
{
alert("Your stare is interrupted by the arrival of a huge troll.");
scene=7;
}
}
else if (scene==6)
{
scene=0;
}
else if (scene==7)
{
if(num==1)
{
alert("Sorry, a troll lives on the other side of the bridge and you just became his lunch.");
scene=6;
}
else if (num ==2)
{
scene=9;
}
}
document.getElementById("img").src ="scene"+scene+".png";
}
</script>
</head>
<body>
<div style="margin: 0 auto; text-align:center">
<img src="scene0.png" alt="Choose your path" id="img"/>
<br />
<input type="button" id="decision1" value="1" onclick="changeImg(1)" />
<input type="button" id="decision2" value="2" onclick="changeImg(2)" />
</div>
</body>
</html>
Subscribe to:
Posts (Atom)
