Monday, May 18, 2009

Payroll System part 2

// Fig. 11.9: PayrollSystemTest.cs
// Employee hierarchy test application.
using System;

public class PayrollSystemTest
{
public static void Main( string[] args )
{
// create derived class objects
SalariedEmployee salariedEmployee =
new SalariedEmployee("John", "Smith", "111-11-1111", "03/10/2002", 800.00M);
HourlyEmployee hourlyEmployee =
new HourlyEmployee( "Karen", "Price",
"222-22-2222","05/10/2000", 16.75M, 40.0M );
CommissionEmployee commissionEmployee =
new CommissionEmployee( "Sue", "Jones",
"333-33-3333", "11/10/2005", 10000.00M, .06M);
BasePlusCommissionEmployee basePlusCommissionEmployee =
new BasePlusCommissionEmployee( "Bob", "Lewis",
"444-44-4444", "05/01/2009",5000.00M, .04M, 300.00M );

SalariedEmployee salariedEmployee2 =
new SalariedEmployee("Ken", "Smith", "555-55-5555", "03/10/2002", 400.00M);
HourlyEmployee hourlyEmployee2 =
new HourlyEmployee("Karen", "Jones",
"666-66-6666", "05/10/2000", 12.75M, 40.0M);
CommissionEmployee commissionEmployee2 =
new CommissionEmployee("Robert", "Jones",
"777-77-7777", "11/10/2005", 10000.00M, .06M);
BasePlusCommissionEmployee basePlusCommissionEmployee2 =
new BasePlusCommissionEmployee("Jessi", "Lewis",
"888-88-8888", "11/01/2009", 1000.00M, .02M, 100.00M);

Console.WriteLine( "Employees processed individually:\n" );

Console.WriteLine( "{0}\n{1}: {2:C}\n",
salariedEmployee, "earned", salariedEmployee.Earnings() );
Console.WriteLine( "{0}\n{1}: {2:C}\n",
hourlyEmployee, "earned", hourlyEmployee.Earnings() );
Console.WriteLine( "{0}\n{1}: {2:C}\n",
commissionEmployee, "earned", commissionEmployee.Earnings() );
Console.WriteLine( "{0}\n{1}: {2:C}\n",
basePlusCommissionEmployee,
"earned", basePlusCommissionEmployee.Earnings() );

// create four-element Employee array
Employee[] employees = new Employee[ 8 ];

// initialize array with Employees of derived types
employees[ 0 ] = salariedEmployee;
employees[ 2 ] = hourlyEmployee;
employees[ 4 ] = commissionEmployee;
employees[ 6 ] = basePlusCommissionEmployee;
employees[1] = salariedEmployee2;
employees[3] = hourlyEmployee2;
employees[5] = commissionEmployee2;
employees[7] = basePlusCommissionEmployee2;
Console.WriteLine( "Employees processed polymorphically:\n" );

// generically process each element in array employees
foreach ( Employee currentEmployee in employees )
{
Console.WriteLine( currentEmployee ); // invokes ToString

// determine whether element is a BasePlusCommissionEmployee
if ( currentEmployee is BasePlusCommissionEmployee )
{
// downcast Employee reference to
// BasePlusCommissionEmployee reference
BasePlusCommissionEmployee employee =
( BasePlusCommissionEmployee ) currentEmployee;

employee.BaseSalary *= 1.10M;
Console.WriteLine(
"new base salary with 10% increase is: {0:C}",
employee.BaseSalary );
} // end if

Console.WriteLine(
"earned {0:C}\n", currentEmployee.Earnings() );
} // end foreach

// get type name of each object in employees array
for ( int j = 0; j < employees.Length; j++ )
Console.WriteLine( "Employee {0} is a {1}", j,
employees[ j ].GetType() );
} // end Main
} // end class PayrollSystemTest


=======================
// Fig. 11.8: BasePlusCommissionEmployee.cs
// BasePlusCommissionEmployee class that extends CommissionEmployee.
public class BasePlusCommissionEmployee : CommissionEmployee
{
private decimal baseSalary; // base salary per week

// six-parameter constructor
public BasePlusCommissionEmployee( string first, string last,
string ssn, string hired, decimal sales, decimal rate, decimal salary )
: base( first, last, ssn, hired,sales, rate )
{
BaseSalary = salary; // validate base salary via property
} // end six-parameter BasePlusCommissionEmployee constructor

// property that gets and sets
// base-salaried commission employee's base salary
public decimal BaseSalary
{
get
{
return baseSalary;
} // end get
set
{
baseSalary = ( value >= 0 ) ? value : 0; // validation
} // end set
} // end property BaseSalary

// calculate earnings; override method Earnings in CommissionEmployee
public override decimal Earnings()
{
return BaseSalary + base.Earnings();
} // end method Earnings

// return string representation of BasePlusCommissionEmployee object
public override string ToString()
{
return string.Format( "{0} {1}; {2}: {3:C}",
"base-salaried", base.ToString(), "base salary", BaseSalary );
} // end method ToString
} // end class BasePlusCommissionEmployee


===========================
// Fig. 11.7: CommissionEmployee.cs
// CommissionEmployee class that extends Employee.
public class CommissionEmployee : Employee
{
private decimal grossSales; // gross weekly sales
private decimal commissionRate; // commission percentage

// five-parameter constructor
public CommissionEmployee( string first, string last, string ssn, string hired,
decimal sales, decimal rate ) : base( first, last, ssn, hired )
{
GrossSales = sales; // validate gross sales via property
CommissionRate = rate; // validate commission rate via property
} // end five-parameter CommissionEmployee constructor

// property that gets and sets commission employee's commission rate
public decimal CommissionRate
{
get
{
return commissionRate;
} // end get
set
{
commissionRate = ( value > 0 && value < 1 ) ?
value : 0; // validation
} // end set
} // end property CommissionRate

// property that gets and sets commission employee's gross sales
public decimal GrossSales
{
get
{
return grossSales;
} // end get
set
{
grossSales = ( value >= 0 ) ? value : 0; // validation
} // end set
} // end property GrossSales
// calculate earnings; override abstract method Earnings in Employee
public override decimal Earnings()
{
return CommissionRate * GrossSales;
} // end method Earnings

// return string representation of CommissionEmployee object
public override string ToString()
{
return string.Format( "{0}: {1}\n{2}: {3:C}\n{4}: {5:F2}",
"commission employee", base.ToString(),
"gross sales", GrossSales, "commission rate", CommissionRate );
} // end method ToString
} // end class CommissionEmployee
=============================
// Fig. 11.4: Employee.cs
// Employee abstract base class.
public abstract class Employee
{
private string firstName;
private string lastName;
private string socialSecurityNumber;
private string dateofHired;
// three-parameter constructor
public Employee( string first, string last, string ssn,string hired )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
dateofHired = hired;
} // end three-parameter Employee constructor

// read-only property that gets employee's first name
public string FirstName
{
get
{
return firstName;
} // end get
} // end property FirstName

// read-only property that gets employee's last name
public string LastName
{
get
{
return lastName;
} // end get
} // end property LastName

// read-only property that gets employee's social security number
public string SocialSecurityNumber
{
get
{
return socialSecurityNumber;
} // end get
} // end property SocialSecurityNumber
public string DateofHired
{
get
{
return dateofHired;
} // end get
} // end property SocialSecurityNumber
// return string representation of Employee object, using properties
public override string ToString()
{
return string.Format( "{0} {1}\nsocial security number: {2}\nDate of Hired: {3}",
FirstName, LastName, SocialSecurityNumber,DateofHired);
} // end method ToString

// abstract method overridden by derived classes
public abstract decimal Earnings(); // no implementation here
} // end abstract class Employee
==============================================

// Fig. 11.5: SalariedEmployee.cs
// SalariedEmployee class that extends Employee.
public class SalariedEmployee : Employee
{
private decimal weeklySalary;

// four-parameter constructor
public SalariedEmployee( string first, string last, string ssn, string hired,
decimal salary ) : base( first, last, ssn, hired )
{
WeeklySalary = salary; // validate salary via property
} // end four-parameter SalariedEmployee constructor

// property that gets and sets salaried employee's salary
public decimal WeeklySalary
{
get
{
return weeklySalary;
} // end get
set
{
weeklySalary = ( ( value >= 0 ) ? value : 0 ); // validation
} // end set
} // end property WeeklySalary

// calculate earnings; override abstract method Earnings in Employee
public override decimal Earnings()
{
return WeeklySalary;
} // end method Earnings

// return string representation of SalariedEmployee object
public override string ToString()
{
return string.Format( "salaried employee: {0}\n{1}: {2:C}",
base.ToString(), "weekly salary", WeeklySalary );
} // end method ToString
} // end class SalariedEmployee

// Fig. 11.5: SalariedEmployee.cs
// SalariedEmployee class that extends Employee.
public class SalariedEmployee : Employee
{
private decimal weeklySalary;

// four-parameter constructor
public SalariedEmployee( string first, string last, string ssn, string hired,
decimal salary ) : base( first, last, ssn, hired )
{
WeeklySalary = salary; // validate salary via property
} // end four-parameter SalariedEmployee constructor

// property that gets and sets salaried employee's salary
public decimal WeeklySalary
{
get
{
return weeklySalary;
} // end get
set
{
weeklySalary = ( ( value >= 0 ) ? value : 0 ); // validation
} // end set
} // end property WeeklySalary

// calculate earnings; override abstract method Earnings in Employee
public override decimal Earnings()
{
return WeeklySalary;
} // end method Earnings

// return string representation of SalariedEmployee object
public override string ToString()
{
return string.Format( "salaried employee: {0}\n{1}: {2:C}",
base.ToString(), "weekly salary", WeeklySalary );
} // end method ToString
} // end class SalariedEmployee


Lab 17 Be sure to put each class in its own file. Add a dateHired property to the base class. Add one additional employee of each type to the vector. Give them each unique names and other properties.

Employee Payroll System

Lab 16 Be sure to put each class in its own file. Add a property to the base class, e.g. numberOfDependents or yearOfBirth. Add code that uses (prints) the new property. Add an additional employee beyond the ones in the sample program.

// Fig. 10.18: ConstructorTest.cs
// Display order in which base class and derived class constructors
// are called.
using System;

public class ConstructorTest
{
public static void Main( string[] args )
{
CommissionEmployee4 employee1 = new CommissionEmployee4( "Bob",
"Lewis", "333-33-3333", 5, 5000.00M, .04M );

CommissionEmployee4 employee5 = new CommissionEmployee4("Mason",
"Lewis", "444-44-4444", 2, 5000.00M, .04M);
} // end Main
} // end class ConstructorTest

============================================================================
// Fig. 10.17: BasePlusCommissionEmployee5.cs
// BasePlusCommissionEmployee5 class declaration.
using System;

public class BasePlusCommissionEmployee5 : CommissionEmployee4
{
private decimal baseSalary; // base salary per week

// six-parameter derived class constructor
// with call to base class CommissionEmployee4 constructor
public BasePlusCommissionEmployee5( string first, string last,
string ssn, int depend, decimal sales, decimal rate, decimal salary )
: base( first, last, ssn, depend, sales, rate )
{
BaseSalary = salary; // validate base salary via property

Console.WriteLine(
"\nBasePlusCommissionEmployee5 constructor:\n" + this );
} // end six-parameter BasePlusCommissionEmployee5 constructor

// property that gets and sets
// base-salaried commission employee's base salary
public decimal BaseSalary
{
get
{
return baseSalary;
} // end get
set
{
baseSalary = ( value < 0 ) ? 0 : value;
} // end set
} // end property BaseSalary

// calculate earnings
public override decimal Earnings()
{
return BaseSalary + base.Earnings();
} // end method Earnings

// return string representation of BasePlusCommissionEmployee5
public override string ToString()
{
return string.Format( "{0} {1}\n{2}: {3:C}",
"base-salaried", base.ToString(), "base salary", BaseSalary );
} // end method ToString
} // end class BasePlusCommissionEmployee5

================================================================
// Fig. 10.16: CommissionEmployee4.cs
// CommissionEmployee4 class represents a commission employee.
using System;

public class CommissionEmployee4
{
private string firstName;
private string lastName;
private string socialSecurityNumber;
private decimal grossSales; // gross weekly sales
private decimal commissionRate; // commission percentage
private int depend;
// five-parameter constructor
public CommissionEmployee4( string first, string last, string ssn, int depends,
decimal sales, decimal rate )
{
// implicit call to object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
GrossSales = sales; // validate gross sales via property
CommissionRate = rate; // validate commission rate via property
depend = depends;
Console.WriteLine( "\nCommissionEmployee4 constructor:\n" + this );
} // end five-parameter CommissionEmployee4 constructor

// read-only property that gets commission employee's first name
public string FirstName
{
get
{
return firstName;
} // end get
} // end property FirstName

// read-only property that gets commission employee's last name
public string LastName
{
get
{
return lastName;
} // end get
} // end property LastName

// read-only property that gets
// commission employee's social security number
public string SocialSecurityNumber
{
get
{
return socialSecurityNumber;
} // end get
} // end property SocialSecurityNumber

// property that gets and sets commission employee's gross sales
public int Depend
{
get
{
return depend;
} //end get
}
public decimal GrossSales
{
get
{
return grossSales;
} // end get
set
{
grossSales = ( value < 0 ) ? 0 : value;
} // end set
} // end property GrossSales

// property that gets and sets commission employee's commission rate
public decimal CommissionRate
{
get
{
return commissionRate;
} // end get
set
{
commissionRate = ( value > 0 && value < 1 ) ? value : 0;
} // end set
} // end property CommissionRate

// calculate commission employee's pay
public virtual decimal Earnings()
{
return CommissionRate * GrossSales;
} // end method Earnings

// return string representation of CommissionEmployee object
public override string ToString()
{
return string.Format(
"{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}:{10}",
"commission employee", FirstName, LastName,
"social security number", SocialSecurityNumber,
"gross sales", GrossSales, "commission rate", CommissionRate
,"Number of Dependants", Depend);
} // end method ToString
} // end class CommissionEmployee4

Wednesday, May 13, 2009

Lab 9 Operator

Lab 9 Use the reference code as a hint. Your program will be quite different. Ask the user for 2 values. Accept string values from the user. Define two boolean variables. Set the boolean variables according to what is entered. For example, “T”, “t”, “True”, etc. should be regarded as TRUE. After accepting and converting the user input to boolean, report both the input values and the result of the logical operators (&, &&, |, ||, ^ and !) on the entered values. Put all this in a loop and accept ‘q’ for value 1 as the signal to quit. Print an error message and resume looping if an Invalid value is entered.

// Fig. 6.18: LogicalOperators.cs
// Logical operators.
using System;

public class LogicalOperators
{
public static void Main( string[] args )
{
Boolean value1=true, value2=true; // get two values from users.
string string1, string2="true"; //string from input
Boolean string1ok = true, string2ok = true;
do
{
Console.WriteLine("Please enter the first boolean value, press q to quit!");
string1=Convert.ToString(Console.ReadLine());
if (string1 == "T" || string1 == "True" || string1 == "t" || string1 == "true")
{
value1 = true;
}
else
if (string1 == "f" || string1 == "False" || string1 == "F" || string1 == "false")
{
value1 = false;
}
else string1ok = false;
if (string1 != "q" && string1 != "Q")
{
Console.WriteLine("Please enter the second boolean value");
string2 = Convert.ToString(Console.ReadLine());
}
if (string2 == "T" || string2 == "True" || string2 == "t" || string2 == "true")
{
value2 = true;
}
else
if (string2 == "f" || string2 == "False" || string2 == "F" || string2 == "false")
{
value2 = false;
}
else string2ok = false;
if ((string1ok == true) && (string2ok == true))
{
// create truth table for && (conditional AND) operator
Console.WriteLine("First String is '{0}'\n", string1);
Console.WriteLine("Second String is '{0}'\n", string2);
Console.WriteLine("{0}\n{1}\n",
"Conditional AND (&&)", (value1 && value2));


// create truth table for || (conditional OR) operator
Console.WriteLine("{0}\n{1}\n",
"Conditional or (||)", (value1 || value2));

// create truth table for & (boolean logical AND) operator
Console.WriteLine("{0}\n{1}\n",
"Boolean Logical And (&)", (value1 & value2));

// create truth table for | (boolean logical inclusive OR) operator
Console.WriteLine("{0}\n{1}\n",
"Boolean Logical inclusive or (|)", (value1 | value2));


// create truth table for ^ (boolean logical exclusive OR) operator
Console.WriteLine("{0}\n{1}\n",
"Boolean Logical exclusive or (^)", (value1 ^ value2));


// create truth table for ! (logical negation) operator
value1 = !value1;
value2 = !value2;
Console.WriteLine("{0}\n{1}\n{2}",
"Boolean Logical Negation (!)", value1, value2);
} //end if
if (string1 != "q" && string1 != "Q")
if (string1ok == false || string2ok == false)
Console.WriteLine("Please enter the valid values");

} while (string1!="q" && string1!="Q"); //while loop
Console.WriteLine("Thank you!");
} // end Main
} // end class LogicalOperators

lab 10 Study Gamble with Crap

Lab 10 Be sure to put each class in its own file. Put the craps game in a loop that continues when you press enter and quits only if you enter ‘q’. After each game display the (1) number of games, (2) number of wins, (3) number of loses, (4) percent wins and (5) percent loses.

// Fig. 7.9: Craps.cs
// Craps class simulates the dice game craps.
using System;

public class Craps
{
// create random number generator for use in method RollDice
private Random randomNumbers = new Random();

// enumeration with constants that represent the game status
private enum Status { CONTINUE, WON, LOST }
// enumeration with constants that represent common rolls of the dice
private enum DiceNames
{
SNAKE_EYES = 2,
TREY = 3,
SEVEN = 7,
YO_LEVEN = 11,
BOX_CARS = 12
}

// plays one game of craps
public int Play()
{
// gameStatus can contain CONTINUE, WON or LOST
Status gameStatus = Status.CONTINUE;
int playgame=0;
int myPoint = 0; // point if no win or loss on first roll

int sumOfDice = RollDice(); // first roll of the dice

// determine game status and point based on first roll
switch ( ( DiceNames ) sumOfDice )
{
case DiceNames.SEVEN: // win with 7 on first roll
case DiceNames.YO_LEVEN: // win with 11 on first roll
gameStatus = Status.WON;
break;
case DiceNames.SNAKE_EYES: // lose with 2 on first roll
case DiceNames.TREY: // lose with 3 on first roll
case DiceNames.BOX_CARS: // lose with 12 on first roll
gameStatus = Status.LOST;
break;
default: // did not win or lose, so remember point
gameStatus = Status.CONTINUE; // game is not over
myPoint = sumOfDice; // remember the point
Console.WriteLine( "Point is {0}", myPoint );
break;
} // end switch

// while game is not complete
while ( gameStatus == Status.CONTINUE ) // game not WON or LOST
{
sumOfDice = RollDice(); // roll dice again

// determine game status
if ( sumOfDice == myPoint ) // win by making point
gameStatus = Status.WON;
else
// lose by rolling 7 before point
if ( sumOfDice == ( int ) DiceNames.SEVEN )
gameStatus = Status.LOST;
} // end while
// display won or lost message
if (gameStatus == Status.WON)
{
Console.WriteLine("Player wins");
playgame = playgame + 1;
}
else
Console.WriteLine("Player loses");
return playgame;
} // end method Play

// roll dice, calculate sum and display results
public int RollDice()
{
// pick random die values
int die1 = randomNumbers.Next( 1, 7 ); // first die roll
int die2 = randomNumbers.Next( 1, 7 ); // second die roll

int sum = die1 + die2; // sum of die values

// display results of this roll
Console.WriteLine( "Player rolled {0} + {1} = {2}",
die1, die2, sum );
return sum; // return sum of dice
} // end method RollDice

} // end class Craps

// Fig. 7.10: CrapsTest.cs
// Application to test class Craps.
using System;
public class CrapsTest
{
public static void Main( string[] args )
{
Craps game = new Craps();
String inputkey="n";
int totalgame = 0;
int won = 0;
int lost = 0;
decimal percentwin, percentlost;
while (inputkey != "q" && inputkey != "Q")
{
int win=game.Play(); // play one game of craps
totalgame = totalgame + 1;
won = won + win;
Console.WriteLine("\nTotal Game play {0}", totalgame);
Console.WriteLine("Total Winning Game {0}", won);
lost = totalgame - won;
percentwin = (decimal)won / totalgame * 100;
percentlost = (decimal)lost / totalgame * 100;
Console.WriteLine("Total losing game {0}", lost);
Console.WriteLine("Winning Percentage {0:N} %", percentwin);
Console.WriteLine("Losing Percentage {0:N} % ", percentlost);
Console.WriteLine("Press Enter to continue, Press q to quit!");
inputkey = Convert.ToString(Console.ReadLine());

Console.WriteLine("");

} //while loop

} // end Main
} // end class CrapsTest

Lab 11 Study

Lab 11 Be sure to put each class in its own file. Put the call by reference sample program in a loop. Prompt for and input a value. Use that value for each of the calls. Display the value before and after each call. Repeat until a negative number is entered. Use the entered values in the parameters when you call the procedures.


// Fig. 7.18: ReferenceAndOutputParameters.cs
// Reference, output and value parameters.
using System;

class ReferenceAndOutputParameters
{
// call methods with reference, output and value parameters
public void DemonstrateReferenceAndOutputParameters(int x)
{
int y = x; // initialize y to 5
int z; // declares z, but does not initialize it

// display original values of y and z
Console.WriteLine( "Original value of y: {0}", y );
//Console.WriteLine( "Original value of z: uninitialized\n" );

// pass y and z by reference
SquareRef( ref y ); // must use keyword ref
// must use keyword out

// display values of y and z after they are modified by
// methods SquareRef and SquareOut, respectively
Console.WriteLine( "Value of y after SquareRef: {0}", y );

SquareOut(out y);
Console.WriteLine( "Value of z after SquareOut: {0}\n", y );

// pass y and z by value
Square( y );
//Square( z );

// display values of y and z after they are passed to method Square
// to demonstrate arguments passed by value are not modified
Console.WriteLine( "Value of y after Square: {0}", y );
//Console.WriteLine( "Value of z after Square: {0}", z );
} // end method DemonstrateReferenceAndOutputParameters

// uses reference parameter x to modify caller's variable
void SquareRef( ref int x )
{
x = x * x; // squares value of caller's variable
} // end method SquareRef

// uses output parameter x to assign a value
// to an uninitialized variable
void SquareOut( out int x )
{
x = 6; // assigns a value to caller's variable
x = x * x; // squares value of caller's variable
} // end method SquareOut

// parameter x receives a copy of the value passed as an argument,
// so this method cannot modify the caller's variable
void Square( int x )
{
x = x * x;
} // end method Square
} // end class ReferenceAndOutputParameters

// Fig. 7.19: ReferenceAndOutputParamtersTest.cs
// Application to test class ReferenceAndOutputParameters.
using System;
class ReferenceAndOutputParamtersTest
{
static void Main( string[] args )
{
int number=1;
ReferenceAndOutputParameters test =
new ReferenceAndOutputParameters();
do
{
Console.WriteLine("\nPlease enter a number!");
number = Convert.ToInt16(Console.ReadLine());
if (number >0)
test.DemonstrateReferenceAndOutputParameters(number);

} while (number > 0) ; //end whille

} // end Main
} // end class ReferenceAndOutputParamtersTest

lab 12 study

Lab 12 Be sure to put each class in its own file. Replace the constant values in the grade array with random numbers (integers) from 0 to 100. Accept the number of students and number of tests from the user. Put the whole thing in a loop. Quit when a negative number of students is entered.


// Fig. 8.21: GradeBookTest.cs
// Create GradeBook object using a rectangular array of grades.
using System;
public class GradeBookTest
{
// Main method begins application execution
public static void Main( string[] args )
{
// rectangular array of student grades
int[,] gradesArray;
int studentnumber;
int size=0;
Random randomNumbers = new Random();


do
{
Console.WriteLine("How many students are there");
studentnumber = Convert.ToInt32(Console.ReadLine());
if ((studentnumber >0))
{
Console.WriteLine("How many tests?");
size = Convert.ToInt32(Console.ReadLine());
}
if ((studentnumber>0) && (size>0))
{
gradesArray = new int[studentnumber, size];
for (int x = 0; x < studentnumber; x++)
for (int i = 0; i < size; i++)
gradesArray[x, i] = randomNumbers.Next(0, 100);
GradeBook myGradeBook = new GradeBook(
"CS101 Introduction to C# Programming", gradesArray);
myGradeBook.DisplayMessage();
myGradeBook.ProcessGrades();
}

} while (studentnumber > 0);


} // end Main
} // end class GradeBookTest

// Fig. 8.20: GradeBook.cs
// Grade book using rectangular array to store grades.
using System;

public class GradeBook
{
private string courseName; // name of course this grade book represents
private int[ , ] grades; // rectangular array of student grades

// two-parameter constructor initializes courseName and grades array
public GradeBook( string name, int[ , ] gradesArray )
{
CourseName = name; // initialize courseName
grades = gradesArray; // initialize grades array
} // end two-parameter GradeBook constructor

// property that gets and sets the course name
public string CourseName
{
get
{
return courseName;
} // end get
set
{
courseName = value;
} // end set
} // end property CourseName

// display a welcome message to the GradeBook user
public void DisplayMessage()
{

Console.WriteLine( "Welcome to the grade book for\n{0}!\n",
CourseName );
} // end method DisplayMessage

// perform various operations on the data
public void ProcessGrades()
{
// output grades array
OutputGrades();

// call methods GetMinimum and GetMaximum
Console.WriteLine( "\n{0} {1}\n{2} {3}\n",
"Lowest grade in the grade book is", GetMinimum(),
"Highest grade in the grade book is", GetMaximum() );

// output grade distribution chart of all grades on all tests
OutputBarChart();
} // end method ProcessGrades

// find minimum grade
public int GetMinimum()
{
// assume first element of grades array is smallest
int lowGrade = grades[ 0, 0 ];

// loop through elements of rectangular grades array
foreach ( int grade in grades )
{
// if grade less than lowGrade, assign it to lowGrade
if ( grade < lowGrade )
lowGrade = grade;
} // end foreach

return lowGrade; // return lowest grade
} // end method GetMinimum

// find maximum grade
public int GetMaximum()
{
// assume first element of grades array is largest
int highGrade = grades[ 0, 0 ];

// loop through elements of rectangular grades array
foreach ( int grade in grades )
{
// if grade greater than highGrade, assign it to highGrade
if ( grade > highGrade )
highGrade = grade;
} // end foreach

return highGrade; // return highest grade
} // end method GetMaximum

// determine average grade for particular student
public double GetAverage( int student )
{
// get the number of grades per student
int amount = grades.GetLength( 1 );
int total = 0; // initialize total

// sum grades for one student
for ( int exam = 0; exam < amount; exam++ )
total += grades[ student, exam ];

// return average of grades
return ( double ) total / amount;
} // end method GetAverage

// output bar chart displaying overall grade distribution
public void OutputBarChart()
{
Console.WriteLine( "Overall grade distribution:" );

// stores frequency of grades in each range of 10 grades
int[] frequency = new int[ 11 ];

// for each grade in GradeBook, increment the appropriate frequency
foreach ( int grade in grades )
{
++frequency[ grade / 10 ];
} // end foreach

// for each grade frequency, print bar in chart
for ( int count = 0; count < frequency.Length; count++ )
{
// output bar label ( "00-09: ", ..., "90-99: ", "100: " )
if ( count == 10 )
Console.Write( " 100: " );
else
Console.Write( "{0:D2}-{1:D2}: ",
count * 10, count * 10 + 9 );

// print bar of asterisks
for ( int stars = 0; stars < frequency[ count ]; stars++ )
Console.Write( "*" );

Console.WriteLine(); // start a new line of output
} // end outer for
} // end method OutputBarChart

// output the contents of the grades array
public void OutputGrades()
{
Console.WriteLine( "The grades are:\n" );
Console.Write( " " ); // align column heads

// create a column heading for each of the tests
for ( int test = 0; test < grades.GetLength( 1 ); test++ )
Console.Write( "Test {0} ", test + 1 );

Console.WriteLine( "Average" ); // student average column heading

// create rows/columns of text representing array grades
for ( int student = 0; student < grades.GetLength( 0 ); student++ )
{
Console.Write( "Student {0,2}", student + 1 );

// output student's grades
for ( int grade = 0; grade < grades.GetLength( 1 ); grade++ )
Console.Write( "{0,8}", grades[ student, grade ] );

// call method GetAverage to calculate student's average grade;
// pass row number as the argument to GetAverage
Console.WriteLine( "{0,9:F2}",GetAverage( student ) );
} // end outer for
} // end method OutputGrades
} // end class GradeBook

Lab 13 Study

Lab 13 Be sure to put each class in its own file. The referenced pages contain four short programs that demonstrate string functions. Combine logic from these programs to create your own big program that demonstrates these string functions. Put all this in a loop. Accept one or more strings from the user and use these strings in the string functions in your program.

// Fig. 16.5: StringIndexMethods.cs
// Using string searching methods.
using System;

class StringIndexMethods
{
public static void Main()
{

string string1, string2, string3, inputkey;
inputkey = "n";
while (inputkey != "q" && inputkey != "Q")
{

Console.WriteLine("\nPlease Enter the first string");
string1=Convert.ToString(Console.ReadLine());
Console.WriteLine("\nPlease Enter the second string");
string2=Convert.ToString(Console.ReadLine());
string3=string.Concat( string1, string2 );

Console.WriteLine("The Concat of the String1 and String2 is {0}", string3);
Console.WriteLine( "\nstring1.ToUpper() = \"" +
string1.ToUpper() + "\"\nstring2.ToLower() = \"" +
string2.ToLower() + "\"" );

// call Trim method
Console.WriteLine( "\nstring3 after trim = \"" +
string3.Trim() + "\"" );

if (string1.Contains("a")==true)
{
Console.WriteLine(
"\nReplacing \"a\" with \"A\" in string1: \"" +
string1.Replace( 'a', 'A' ) + "\"" );
}
Console.WriteLine("\nThe length of the String 1 is " + string1.Length);
Console.WriteLine("\nThe length of the String 2 is " + string2.Length);
Console.WriteLine("\nThe length of the String 3 is " + string3.Length);
Console.WriteLine( "\nstring1 = \"" + string1 + "\"" );

Console.WriteLine("Press Enter to continue, Press q to quit!");
inputkey = Convert.ToString(Console.ReadLine());

Console.WriteLine("");

} //while loop






} // end method Main
} // end class StringIndexMethods

LAB 14

Lab 14 Be sure to put each class in its own file. Add the “weight” property to the box. Accept the property values from the console and then display them. Put the whole thing in a loop. Enter ‘q’ to quit. Display a message if a number is not entered.

// Fig. 9.6: BoxTest.cs
// Indexers provide access to a Box object's members.
using System;

public class BoxTest
{
public static void Main( string[] args )
{
// create a box
Box box = new Box( 30, 30, 30, 30 );
string inputkey;
// show dimensions with numeric indexers
Console.WriteLine( "Created a box with the dimensions:" );
Console.WriteLine( "box[ 0 ] = {0}", box[ 0 ] );
Console.WriteLine( "box[ 1 ] = {0}", box[ 1 ] );
Console.WriteLine( "box[ 2 ] = {0}", box[ 2 ] );
Console.WriteLine("box[ 3]= {0}", box[3]);

inputkey = "n";
while (inputkey != "q" && inputkey != "Q")
{

// show dimensions with string indexers
Console.WriteLine("Welcome to UPS Center!");
Console.WriteLine("Please enter the Width");
box["width"] = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the length");
box["length"] = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the height");
box["height"] = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the weight");
box["weight"] = Convert.ToDouble(Console.ReadLine());

Console.WriteLine( "Now the box has the dimensions:" );
Console.WriteLine( "box[ \"length\" ] = {0}", box[ "length" ] );
Console.WriteLine( "box[ \"width\" ] = {0}", box[ "width" ] );

Console.WriteLine( "box[ \"height\" ] = {0}", box[ "height" ] );
Console.WriteLine("box[ \"weight\" ] = {0}", box["weight"]);

Console.WriteLine("Press Enter to continue, Press q to quit!");
inputkey = Convert.ToString(Console.ReadLine());

Console.WriteLine("");

} //while loop
Console.WriteLine("Thank you!");
} // end method Main
} // end class BoxTest


// Fig. 9.5: Box.cs
// Box class definition represents a box with length,
// width and height dimensions with indexers.
public class Box
{
private string[] names = { "length", "width", "height", "weight"};
private double[] dimensions = new double[ 4];

// constructor
public Box( double length, double width, double height, double weight )
{
dimensions[ 0 ] = length;
dimensions[ 1 ] = width;
dimensions[ 2 ] = height;
dimensions[3] = weight;
}

// indexer to access dimensions by integer index number
public double this[ int index ]
{
get
{
// validate index to get
if ( ( index < 0 ) || ( index >= dimensions.Length ) )
return -1;
else
return dimensions[ index ];
} // end get
set
{
if ( index >= 0 && index < dimensions.Length )
dimensions[ index ] = value;
} // end set
} // end numeric indexer

// indexer to access dimensions by their string names
public double this[ string name ]
{
get
{
// locate element to get
int i = 0;
while ( ( i < names.Length ) &&
( name.ToLower() != names[ i ] ) )
i++;

return ( i == names.Length ) ? -1 : dimensions[ i ];
} // end get
set
{
// locate element to set
int i = 0;
while ( ( i < names.Length ) &&
( name.ToLower() != names[ i ] ) )
i++;

if ( i != names.Length )
dimensions[ i ] = value;
} // end set
} // end string indexer
} // end class Box

LAB 15

Lab 15 Be sure to put each class in its own file. Enhance the ComplexNumber class by overloading the / (division) operator. The implementation does not have to be mathematically precise. Accept the input values from the keyboard. Put the whole thing in a loop and provide an appropriate way to terminate the loop.

// Fig 11.18: OperatorOverloading.cs
// Overloading operators for complex numbers.
using System;

public class ComplexTest
{
public static void Main( string[] args )
{
// declare two variables to store complex numbers
// to be entered by user
ComplexNumber x, y;
string inputkey;
inputkey = "n";
while (inputkey != "q" && inputkey != "Q")

{
// prompt the user to enter the first complex number
Console.Write( "Enter the real part of complex number x: " );
double realPart = Convert.ToDouble( Console.ReadLine() );
Console.Write(
"Enter the imaginary part of complex number x: " );
double imaginaryPart = Convert.ToDouble( Console.ReadLine() );
x = new ComplexNumber( realPart, imaginaryPart );

// prompt the user to enter the second complex number
Console.Write( "\nEnter the real part of complex number y: " );
realPart = Convert.ToDouble( Console.ReadLine() );
Console.Write(
"Enter the imaginary part of complex number y: " );
imaginaryPart = Convert.ToDouble( Console.ReadLine() );
y = new ComplexNumber( realPart, imaginaryPart );
// display the results of calculations with x and y
Console.WriteLine();
Console.WriteLine( "{0} + {1} = {2}", x, y, x + y );
Console.WriteLine( "{0} - {1} = {2}", x, y, x - y );
Console.WriteLine( "{0} * {1} = {2}", x, y, x * y );
Console.WriteLine("{0} / {1} = {2}", x, y, x / y);
Console.WriteLine("Press Enter to continue, Press q to quit!");
inputkey = Convert.ToString(Console.ReadLine());

Console.WriteLine("");

} //while loop
Console.WriteLine("Thank you!");

} // end method Main
} // end class ComplexTest


// Fig. 11.17: ComplexNumber.cs
// Class that overloads operators for adding, subtracting
// and multiplying complex numbers.
using System;

public class ComplexNumber
{
private double real; // real component of the complex number
private double imaginary; // imaginary component of the complex number

// constructor
public ComplexNumber( double a, double b )
{
real = a;
imaginary = b;
} // end constructor

// return string representation of ComplexNumber
public override string ToString()
{
return string.Format( "({0} {1} {2}i)",
Real, ( Imaginary < 0 ? "-" : "+" ), Math.Abs( Imaginary ) );
} // end method ToString

// read-only property that gets the real component
public double Real
{
get
{
return real;
} // end get
} // end property Real

// read-only property that gets the imaginary component
public double Imaginary
{
get
{
return imaginary;
} // end get
} // end property Imaginary

// overload the addition operator
public static ComplexNumber operator+(
ComplexNumber x, ComplexNumber y )
{
return new ComplexNumber( x.Real + y.Real,
x.Imaginary + y.Imaginary );
} // end operator +

// overload the subtraction operator
public static ComplexNumber operator-(
ComplexNumber x, ComplexNumber y )
{
return new ComplexNumber( x.Real - y.Real,
x.Imaginary - y.Imaginary );
} // end operator -

// overload the multiplication operator
public static ComplexNumber operator*(
ComplexNumber x, ComplexNumber y )
{
return new ComplexNumber(
x.Real * y.Real - x.Imaginary * y.Imaginary,
x.Real * y.Imaginary + y.Real * x.Imaginary );
} // end operator *
public static ComplexNumber operator /(
ComplexNumber x, ComplexNumber y)
{
return new ComplexNumber(
x.Real / y.Real - x.Imaginary / y.Imaginary,
x.Real / y.Imaginary + y.Real / x.Imaginary);
} // end operator /
} // end class ComplexNumber

Thursday, May 7, 2009

Creating Web Page Forms

•Creating Web Page Forms
•Designing a Product Registration Form
•Objectives
•Describe how Web forms can interact with a server-based program
•Insert a form into a Web page
•Create and format an input box for simple text data
•Add a form label and link it to a control element
•Objectives
•Set up a selection list for a predefined list of data values
•Create option buttons for a list of possible field values
•Organize fields into field sets
•Insert a text area box for multiple lines of text data
•Objectives
•Generate form buttons to submit or reset a form
•Describe how data is sent from a Web form to a server
•Understand how to create image fields, hidden fields, and file buttons
•Apply tab indices and access keys to control elements
•Introducing Web Forms
•Web forms collect information from customers
•Web forms include different control elements including:
–Input boxes
–Selection lists
–Drop-down lists boxes
–Option buttons or radio buttons
–Check boxes
–Group boxes
–Text areas
–Form buttons
•Forms and Server-Based Programs
•While HTML supports the creation of forms, it does not include tools to process the information
•The information can be processed through a program running on a Web server
•Forms and Server-Based Programs
•Server-based programs are written in many languages
•The earliest and most commonly used are Common Gateway Interface (CGI) scripts that are written in perl
•Other popular languages include:
–AppleScript - PHP
–ASP - TCL
–ColdFusion - the Unix shell
–C/C++ - Visual Basic
•Creating the Form Element
•Creating the Form Element
•Creating the Form Element
•Creating Input Boxes
•The general syntax of input elements is as follows:
Where type specifies the type of input field,
and the name and id attributes provide the
field’s name and id.
•Creating Input Boxes
•Input types:
type=“button”
Displays a button that can be clicked to perform an action from a script
type=“checkbox
Displays a check box
type=“file”
Displays a browse button to locate and select a file
type=“hidden”
Creates a hidden field, not viewable on the form
•Creating Input Boxes
•Input types:
type=“image”
Displays an input image that can be clicked to perform an action from a script
type=“password”
Displays an input box that hides text entered by the use
type=“radio”
Displays an option button
•Creating Input Boxes
•Input types:
type-”reset”
Displays a button that resets the form when clicked
type=“submit”
Displays a button that submits the form when clicked
type=“text”
Displays an input box that displays text entered by the user
•Setting the Size of an Input Box
•By default, an input box displays at 20 characters of text
•To change the width of an input box, use the size attribute which is displayed as follows:
Where value is the size of the input box in characters.
•Setting the Size of an Input Box
•Creating a Password Field
•A password field is an input box where characters typed by the user are displayed as bullets or asterisks to protect private or sensitive information on a Web site
•The syntax for creating a Password field is as follows:

•Creating an input box
•To create an input box, use the following HTML code:
value=“value” size=“value”
maxlength=“value’ />
Where the name and id attributes identify the field, the value
attribute assigns the field’s default value, the size attribute
defines the width of the input box in characters, and the
maxlength attribute specifies the maximum number of
characters that a user can enter into the field.
•Working with Form Labels
•You can also expressly link a label with an associated text element for scripting purposes
•The syntax for creating a form label is as follows:

Where id is the value of the id attribute for a field on the form, and label text is the text of the label.
•Creating a Selection List
•A selection list is a list box from which a user selects a particular value or set of values
–Selection lists are useful when there are a fixed set of possible responses from the user
•You can create a selection list using the
Where value is the number of items that the selection list displays in the form.
•Modifying the Appearance of a Selection List
•Making Multiple Selections
•Add the multiple attribute to the select element to create multiple selections

•Working with Option Groups
•Use option groups to organize selection lists into distinct groups.








•Creating Option buttons
•Option buttons, or radio buttons allow users to make selections.
–Unlike selection lists, option buttons only allow the user to select one option at a time.
•Creating a Field Set
•HTML and XHML allow you to organize option buttons into a group of fields called field sets
–Most browsers place a group box around a field set to indicate that the fields belong to a common group

fields

Where fields are the individual fields within a set.
•Creating a Field Set
•To create a field set, enclose the fields in the following tags:
fields

Where fields are the form fields in the field set. Field sets are
usually displayed in a group box
•Creating a Field Set
•To add a caption to a field set, add the following tag after the opening
tag:
text
Where text is the text of the field set caption.
•Creating Check Boxes
•To create a check box, use:
""
Where the name and id attributes identify the check box field and
the value attribute specifies the value sent to the server if the check
box is selected
•To specify that a check box be selected by default, use the checked attribute as follows:

or

•Creating a Text Area Box
•Text area boxes allow users to enter comments about the products they’ve purchased
•An input box would be too small to accommodate the length of text for this use
•Creating a Text Area Box
•To create a text area box, use the textarea element:

Where the rows and cols attributes define the
dimensions of the input box and the rows attribute
indicates the number of lines in the input box
•Creating a Text Area Box
•Wrap values
•Wrap=“off”
•Wrap=“soft”
•Wrap=“hard”
•Working with Form Buttons
•Buttons are a type of control element that performs an action
•Types of buttons:
–Command button
–Submit button
–Reset button
–File button
•Creating a Command button
•Command buttons are created using the tag:

•Submit buttons submit forms to the server for processing when clicked. Syntax is as follows:

•Reset buttons reset forms to their original (default) values. Syntax is as follows:

•Completed Registration Form
•Designing a Command button
•Use the button element for greater artistic control over the appearance of a button

Where the name and value attributes specify the name of the button
and the value sent to a server-based program, the id attribute
specifies the button’s id, the type attribute specifies the button type,
and the content is page content displayed within the button.
•Creating a File button
•File buttons are used to select files so that their contents can be submitted for processing to a program.
•The Web page then only displays the file’s location, not the file’s contents.
•Working with Hidden Fields
•Hidden fields are added to a form, but not displayed in the Web page. The syntax is as follows:
value=“value” />
•Working with Form Attributes
•After adding the elements to your form, you’ll need to specify where to send the form data and how to send it. Use the following attributes:

Where url specifies the filename and location of the program that processes
the form and the method attribute specifies how your Web browser sends
data to the server. The enctype attribute specifies the format of the data
stored in the form’s field.
•Working with Form Attributes
•The method attribute can have one of two values:
–Post
–Get
•The get method is the default; get appends the form data to the end of the URL specified in the action attribute
•The post method sends form data in a separate data stream, allowing the Web server to receive the data through “standard input”
•Using the mailto Action
•The mailto action accesses the user’s own e-mail program and uses it to mail form information to a specified e-mail address
–By-passes the need for server-based programs
•The syntax is as follows:
mailto:e-mail_address method=“post”
enctype=“text/plain”> …

Where e-mail_address is the e-mail address of the recipient in the form
•Specifying the Tab Order
•Users typically navigate through a form with the tab key
•You can specify an alternate tab order by adding the tabindex attribute to any control element in your form
•The syntax is as follows:

This syntax assigns the tab index number “1” to the fname field from the
registration form
•Specifying an Access Key
•An access key is a single key typed with the Alt key (Windows) or Control key (Mac), in order to jump to one of the control elements in the form
•Create an access key by adding the accesskey attribute to any control element
•Example of creating an access key for the lname field:

Tip for Creating Forms

Tips for Creating Effective Forms
Label all control elements clearly and concisely
Use horizontal lines, tables, and line breaks to separate topical groups from one another
Use field sets to organize common groups of fields, especially option buttons
Use the tab order to ensure that users will move correctly from one field to another
Tips for Creating Effective Forms
Use option buttons, check boxes, and selection lists whenever possible to limit a user’s choice of entries, thus reducing the chance of an erroneous data value. Use input boxes only when the field has no predefined list of values.
Use selection lists for items with several possible options. Use option buttons for items with few options. Use a check box for each item with only two possible values.
Tips for Creating Effective Forms
Let users know the correct format for input box text by inserting default text in the appropriate format (for example, insert the text string, “mm/dd/yyyy” in a Date input box to indicate the format for inserting date values
Use password fields for sensitive or confidential information (such as passwords)
Because form elements differ between browsers, view your form on different browsers and different browser versions to ensure that the form displays correctly in all situations

Working with Box Model

The Box Model
Working with the Box Model
Styles to set padding are similar to styles to set margins:
padding-top: value
padding-right: value
padding-bottom: value
padding-left: value

Border Styles
Border Style Types
Using Pseudo-Classes and Pseudo-Elements
A pseudo-class is a classification of an element based on its status, position, or current use in the document
Using Pseudo-Classes and Pseudo-Elements
Rollover effects can be created using pseudo-classes
Pseudo-elements are elements based on information about an element’s content, use or position
Positioning Objects with CSS
Working with Overflow and Clipping
Stacking Elements
Working with Different Media
The @media Rule
Media Groups
Media Groups
Hiding Elements
Comparing the visibility and display styles
Using Print Styles

Using Multimedia on the Web

•Using Multimedia on the Web
•Enhancing a Web Site with Sound, Video, and Applets
•Objectives
•Working with Multimedia
•Working with Audio
•Linking to an Audio Clip
•Embedding an Audio Clip
•Objectives
•Working with Video
•Linking to a Video Clip
•Embedding a Video Clip
•Using a Dynamic Source
•Supporting Non-Embedded Elements
•Objectives
•Introducing Java
•Working with Applets
•Creating a Marquee with Internet Explorer
•Working with the Object Element
•Working with Multimedia
•Bandwidth is a measure of the amount of data that can be sent through a communication pipeline each second
–Consider bandwidth when working with multimedia on a Web site
•Working with Multimedia
•Multimedia can be added to a Web page two different ways:
–External media is a sound of video file that’s accessed through a link
•Useful for a low bandwidth
–Inline media is placed within a Web page as an embedded object
•Working with Multimedia
•Working with Audio
•Every sound wave is composed of two components:
–Amplitude- the height of the wave. Amplitude relates to the sound’s volume (the higher the amplitude, the louder the sound).
–Frequency- the speed at which the sound wave moves. Frequency relates to sound pitch (high frequencies have high pitches).
•Working with Audio
•Sampling Rate, Sample Resolution, and Channels
•Sound waves are analog functions (represent a continuously varying signal)
–To store the information, however, it must be converted to pieces of information.
•Digital recording measures the sound’s amplitude at discrete moments in time
–Each measurement is called a sample
•Samples per second taken is called the sampling rate
•Sampling Rate
•Sampling Rate, Sample Resolution, and Channels
•Sampling resolution indicates the precision in measuring the sound within each sample
–8-bit
–16-bit
–32-bit
•Sample Resolution
•Sample Rates and Resolution
Sampling rate and sample resolution as
related to sound quality:
Sampling Rate and Sample Resolution Sound Quality
8 KHz, 8-bit, mono Telephone
22 KHz, 16-bit, stereo Radio
44 KHz, 16-bit, stereo CD
48 KHz, 16-bit, stereo Digital Audio Tape (DAT)
•Sound File Formats
•There are different sound file formats used for different operating systems
•Different file formats provide varying levels of sound quality and sound compression
•Sound File Formats
•WAV
•Nonstreaming media
•Streaming media
•MIDI
•Sound File Formats
•MP3 is a version of the MPEG format, which compresses audio files with minor impact on sound quality
–One controversy around the MP3 format involves copyrighted material that has been copied as MP3 without the permission of the artist or producers
•Sound File Formats
•Nonstreaming media must be completely downloaded by users before being played
–May produce lengthy delays
•Sound File Formats
•Streaming media are processed in a steady and continuous stream as they are downloaded by the browser
–Both sound and video
•Sound File Formats
•MIDI (Musical Instrument Digital Interface) converts an analog signal to a series of functions describing the pitch, length, and volume of each note
–MIDI format is limited to instrumental music and cannot be used for general sounds, such as speech
•Linking to an Audio Clip
•Embedding an Audio Clip
•An embedded object is any media clip, file, program, or other object that can be run or viewed from within a Web page
–Browsers need the appropriate plug-ins to run embedded objects
•Embedding an Audio Clip
(Internet Explorer and Netscape)
To embed a sound or video clip, use the
embed element:
"height=“value” autostart=“type” />"
Where url is the location of the object, the width and height
attributes specify the width and the height of the object in pixels,
and type is either true (to start the clip automatically when the page
loads) or false (to start the clip manually).
•Playing Background Sounds
•Internet Explorer (with Version 3.0) introduced an element to play background sounds:
loop=“value” volume=“value” />
Where url is the URL of the sound file, the balance attribute defines
how the sound should be balanced between left and right
speakers, loop defines how many times the sound clip is played,
and the volume attribute indicates the background sound volume.
•Working with Video
•Video files add a visual element to a Web page as well as provide information
•Video files are composed of a series of single images called frames
•The number of frames shown in a period of time is the frame rate
•Frame Rates and Codecs
•Reducing the frame rate reduces the size of your file
–This is one way to control file size of video files
•Using a Codec (compression/decompression) is another way to control the file size

•Video File Formats
•Linking to a Video Clip
•Follow the same procedure to link a video clip as you would to link a sound clip
–Include information about the size of each video file so that users can determine whether they want to retrieve the clip
•Embedding a Video Clip
•Use the same embed element to embed a video file as you did to embed a sound clip
–You must specify a source for an embedded video clip with the src attribute and a size for the clip using the height and width attributes
•Using a Dynamic Source
•To turn inline images into dynamic video clips, use the following syntax:
"loop=“value” control=“control” / />"
Where the dynsrc attribute specifies the URL of a
dynamic (video) version of the inline image. The start attribute tells
the browser when to start the clip, the loop attribute specifies the
number of times the video will play, and the control attribute
specifies whether IE should display player controls below the inline
image to start and stop the video clip.
•Supporting Non-Embedded Elements
•If you want to support older browsers, you can add the noembed element
•The noembed element works like the noframe element for frames, providing a way to support older browsers that do not recognize embedded objects
•Using Non-Embedded Content
To provide alternate content for browsers that don’t support embedded objects, use the code
""
"" <br /> alternate content <br />""
where alternate content is the content displayed by browsers that don’t support embedded objects
•Introducing Java
•Oak was developed by Sun Microsystems as an operating system intended to be used by common appliances and devices
•Oak was renamed Java in 1995
•HotJava runs programs written in the Java language
–HotJava is a Java interpreter (it understands and runs Java languages)
•Applets and Java Interpreters
•Applets
•Applets are displayed as embedded objects on a Web page in an applet window
•Use a Java Developer’s Kit (JDK) to write your own Java applet
•Compiling changes the file into an executable file that can run by itself without the JDK
–The executable file is called a class file
•Working with Applets
•Inserting a Java Applet
•To insert a Java applet, use the code





Where file is the name of the Java class file, text is the
name of an applet parameter, and value is the parameter’s
value.
•Creating a Marquee with Internet Explorer
•An alternative to using an applet to create a box with scrolling text is to create a marquee element
content
Where attributes is one or more of the marquee
elements, and content is the page content that appears
in the marquee box.


Working with the Object Element

•Working with the Object Element
•The object element is the generic element for any object whose content is stored in a file separate from the current Web page
–Inline images
–Sound clips
–Video clips
–Program applets
–Other HTML documents
•Working with the Object Element
•Working with the Object Element
•MIME (Multipurpose Internet Mail Extension) names are used to indicate the type of data using the type attribute in an object element.
•ActiveX
•ActiveX attaches desktop applications to Web pages
•ActiveX objects are referred to as ActiveX controls
•Tips for Using Multimedia
•When linking to multimedia, provide a variety of media formats to ensure that all users have access to formats they can use
•Include the file size in links to large multimedia files to notify users with low bandwidth connections
•Tips for Using Multimedia
•Do not embed multimedia clips in your Web pages unless you are sure that users will be accessing the pages through a high-speed connection
•Do not insert media clips unless you provide a method for users to turn off the clips; if a clip plays automatically, allow it to play only once
•Use the embed and applet elements in preference to the object element because of the broader browser support

Working with cascading Style Sheets

•Working with Cascading Style Sheets
•Creating a Style for Online Scrapbooks
•Objectives
•Introducing Cascading Style Sheets
•Using Inline Styles
•Using Embedded Styles
•Using an External Style Sheet
•Understanding Cascading Order
•Working with Selectors
•Objectives
•Using IDs and Classes
•Sizing Elements
•Floating an Element
•Working with the div Element
•Setting the Display Style
•Working with the Box Model
•Using Pseudo-Classes and Pseudo-Elements
•Applying a Style to a Web Site
•Objectives
•Positioning Objects with CSS
•Working with Overflow and Clipping
•Stacking Elements
•Working with Different Media
•Hiding Elements
•Using Print Styles
•Introducing Cascading Style Sheets
• Style sheets are files or forms that describe the layout and appearance of a document
•Cascading Style Sheets, or CSS, is a style sheet language used on the Web
–CSS specifications are maintained by the World Wide Web Consortium (W3C)
–Three versions of CSS exist: CSS1, CSS2, and CSS3
•Cascading Style Sheets
•CSS1 introduced styles for the following document features:
–Fonts
–Text
–Color
–Backgrounds
–Block-level Elements
•Cascading Style Sheets
•CSS2 introduced styles for the following document features:
–Positioning
–Visual Formatting
–Media Types
–Interfaces
•Cascading Style Sheets
•CSS3 (which is still in development) will introduce styles for the following document features:
–User Interfaces
–Accessibility
–Columnar layout
–International Features
–Mobile Devices
–Scalable Vector Graphics
•Applying a Style Sheet
•Three ways to apply a style to an HTML or XHTML document:
–Inline Styles
–Embedded Styles
–External Styles
•Using Inline Styles
•Inline styles are easy to use and interpret because they are applied directly to the elements they affect.
value2; style3: value3;…”>
•Using Embedded Styles
•You can embed style definitions in a document head using the following form:

Where style declarations are the declarations of the
different styles to be applied to the document

Working with CSS

•Using an External Style Sheet
•Because an embedded style sheet only applies to the content of the start.htm file, you need to place a style declaration in an external style sheet to apply to the headings in the rest of the Web site
•An external style sheet is a text file that contains style declarations
–It can be linked to any page in the site, allowing the same style declaration to be applied to the entire site
•Using an External Style Sheet
•You can add style comments as you develop an external style sheet
•Use the link element to link a Web page to an external style sheet
•You can import the content of one style sheet into another
•Understanding Cascading Order
•You can link a single style sheet to multiple documents in your Web site by using the link element or the @import element
•You can also link a single document to several style sheets
•Applying a single style sheet to multiple documents
•Applying multiple sheets to a single document
•Style Precedence
1.External style sheet
2.Embedded styles
3.Inline styles
•Style Inheritance
•If a style is not specified for an element, it inherits the style of its parent element; This is called style inheritance.
•Working with Selectors
•CSS allows you to work with a wide variety of selectors to match different combinations of elements
•Use contextual selectors to apply a style based on the context in which an element is used
•Simple and contextual selectors
•Attribute Selectors
•Create an attribute selector to select an element based on the element’s attributes
–See figure 7-13 in your text for a list of attribute selectors
•Using IDs and Classes
•Use an id to distinguish something, like a paragraph, from the others in a document
–For example, to identify a paragraph as “head”, use the code:


•Classes
•HTML and XHTML require each id be unique– therefore an id value can only be used once in a document
•You can mark a group of elements with a common identifier using the class attribute

•Applying a style to a class
•STOP
•STOP
•Applying a style to a class and element
•Sizing Elements and Floating an Element
•You can define the width of columns in a columnar layout using: width: value
•You can use CSS to set an element’s height using: height: value
•You can float a paragraph using: float: position
•Working with the div Element
•The div element is a generic block-level element

content

•Setting the Display Style
•Setting the Display Style
•Working with the Box Model
•The box model is an element composed of four sections:
–Margin
–Border
–Padding
–content
•The Box Model
•Working with the Box Model
•Styles to set padding are similar to styles to set margins:
–padding-top: value
–padding-right: value
–padding-bottom: value
–padding-left: value
•Border Styles
•Border Style Types
•Using Pseudo-Classes and Pseudo-Elements
•A pseudo-class is a classification of an element based on its status, position, or current use in the document
•Using Pseudo-Classes and Pseudo-Elements
•Rollover effects can be created using pseudo-classes
•Pseudo-elements are elements based on information about an element’s content, use or position

Positioning Objects with CSS

•The different positioning styles in the original CSS1 specifications were known as CSS-Positioning or CSS-P
•To place an element at a specific position on a page use:
position: type; top: value; right: value;
bottom: value; left: value;

•You can also specify the output media within a style sheet using:
@media type {style declarations}
Where media is one of the supported media types
and style declarations are the styles
associated with that media type

•CSS2 uses media groups to describe basic facets of different media– and to differentiate between different types of media based on the ways they render content
–Continuous or paged
–Visual, aural, or tactile
–Grid (for character grid devices) or bitmap
–Interactive or static

•Two different styles that allow you to hide elements:
–Display style
–Visibility style


•You can specify the size of a page, margins, internal padding, etc. of the page box
•Review the Reference Window on page HTML 420 for working with print styles