Escolar Documentos
Profissional Documentos
Cultura Documentos
Learner Guide
© Copyright, 2016 by North Coast TAFEnow
Date last saved: 21 January 2016 by Amanda Walker Version: 1.0 # of Pages = 57
Copyright of this material is reserved to the Crown in the right of the State of New South Wales.
Reproduction or transmittal in whole, or in part, other than in accordance with the provisions of the Copyright Act, is
prohibited without written authority of North Coast TAFEnow.
Disclaimer: In compiling the information contained within, and accessed through, this document ("Information")
DET has used its best endeavours to ensure that the Information is correct and current at the time of publication but
takes no responsibility for any error, omission or defect therein. To the extent permitted by law, DET and its
employees, agents and consultants exclude all liability for any loss or damage (including indirect, special or
consequential loss or damage) arising from the use of, or reliance on, the Information whether or not caused by any
negligent act or omission. If any law prohibits the exclusion of such liability, DET limits its liability to the extent
permitted by law, to the re-supply of the Information.
Third party sites/links disclaimer: This document may contain website contains links to third party sites. DET is not
responsible for the condition or the content of those sites as they are not under DET's control. The link(s) are
provided solely for your convenience and do not indicate, expressly or impliedly, any endorsement of the site(s) or
the products or services provided there. You access those sites and use their products and services solely at your
own risk.
Contents
Getting Started .................................................................................................................................. i
Icon Legends....................................................................................................................................................................... ii
Visual C# ............................................................................................................................................................................... 1
Arrays ...................................................................................................................................................................................14
Summary ............................................................................................................................................................................19
Abstraction ........................................................................................................................................................................21
Encapsulation ...................................................................................................................................................................23
Inheritance.........................................................................................................................................................................25
Polymorphism ..................................................................................................................................................................27
Composition .....................................................................................................................................................................28
Modularity .........................................................................................................................................................................31
Summary ............................................................................................................................................................................35
Documentation................................................................................................................................................................37
Aggregation ......................................................................................................................................................................39
Code structure..................................................................................................................................................................41
Summary............................................................................................................................................................................ 49
It applies to individuals who are programmers in a variety of fields and who are required to
produce simple programs in object-oriented languages.
Follow this link to find the essential outcomes needed to demonstrate competency in this
Unit: http://training.gov.au
i|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Icon Legends
Learning Activities
Learning activities are the tasks and exercises that assist you in gaining a
clear understanding of the content in this workbook. It is important for you
to undertake these activities, as they will enhance your learning.
Case Studies
Discussions/Live chat
The required reading is referred to throughout this Learner Guide. You will
need the required text for readings and activities.
The suggested reading is quoted in the Learner Guide, however you do not
need a copy of this text to complete the learning. The suggested reading
provides supplementary information that may assist you in completing the
unit.
Reference
A reference will refer you to a piece of information that will assist you with
understanding the information in the Learner Guide or required text.
References may be in the required text, another textbook on the internet.
Self-check
Work Flow
ii | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
iii | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 1 – Visual C# syntax
You will need Visual Studio installed (latest version).
Visual C#
The aim of this section is to learn the syntax of the C# (pronounced See-Sharp) language.
Like any other language, (spoken, written or computer) it has a set of rules that govern its use.
There are several constructs that are important to understand:
> Statements
> Blocks
> Functions
> Classes
1|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The first three of these will be treated in Topic 1.
Creating a project
3 In the dialog that opens click Visual C# in the left pane and Console application in the right
pane
4 Rename the project myFirstProgram in the Name box at the bottom - click OK
2|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
In the next screen, the defaults for the project are created:
The details of these is not important to these notes. However, every program must contain at least
one:
> namespace
> class
Static void Main[] is where the compiler will look for the first instructions to execute.
You may have made use of Intellisense, which offers options to select while you type.
3|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Note how the code is indented to indicate to section to which it belongs.
If not, then there is an error in your code! Revisit the above instructions looking for where you
went wrong. Be specifically mindful of issues like spaces or brackets that are in the wrong
place.
4|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Press enter to terminate the program – the window will then close.
Error Management
Go back to the code, delete the semi colon ( ;) at the end of line 13.
Intellisense will place a red wavy underline as your first defence against errors, much like
Microsoft Word does with spelling errors.
A pop-up error will occur as follows and the output window will describe the error.
5|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 2
Statements
These are pre-defined instructions in the C# language, each with their own purpose.
Declaration
int myNumber;
This tells the compiler to assign a space in memory for an integer named myNumber.
6|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is known as a variable.
When a program runs, the names of the variables created, are not important – they are only
important to programmers reading them.
In all examples and assessments, use this naming convention for all variables:
Join all other words (with no spaces) each starting with an uppercase letter
(ForWeekFour)
Assignment
myNumber = 45;
Using a variable
int myNumber;
myNumber = 45;
Console.WriteLine(myNumber);
Console.ReadLine();
This program
7|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
> assigns the value 45 to myNumber
This program:
> joins the string “You typed” and the value of userValue
> joins the string “The date and time is “ to the variable myDate and writes it to the console
Calculations
function calls
Selection
8|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The IF statement
IF (condition)
else
It is used to add comments to show meaning in the code, for others to read.
Making decisions
9|P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Create a new project and enter this code in the Main[ ] procedure
switch (expression)
{
case value1:
// do something
break;
case value2:
// do something different
break;
case value3:
…
….
default:
// what to do if none of the others match
break;
}
You can include several cases against which the switch may match.
The default case will run if none of the others are matched
Example
10 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
default:
Console.WriteLine("I don't know who you mean");
break;
}
Console.ReadLine();
Use a switch statement like the one above to determine if any of the following are entered:
Iterations (looping)
There are times when the same code needs to be run several times.
1 For loop
2 While loop
For loop
> a condition which must be true (i < 10) otherwise to loop will end.
11 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Here is an example
int i;
for(i=0;i<10;i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
This is typically the only time this is done- as a counter in a for loop.
While loop
while (condition)
{
// do these things repeatedly until (condition) is false
}
If (condition) is false at the start, nothing will be done inside the block.
Example
12 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This line
myString = myString.Substring(0,myString.Length-1);
will assign to myString all but the last character of the string.
The loop will then restart- test if the length is > 0 , write the value and reduce by 1 character.
This process continues until the string is empty (mystring.length > 0 will be false)
The Fibonacci sequence has the property that any number is the sum of the two previous
numbers.
Solution
int firstNumber = 1;
int secondNumber = 1;
int i;
int nextNumber;
Console.WriteLine("The Fibonacci sequence");
Console.WriteLine(firstNumber);
Console.WriteLine(secondNumber);
for(i=3;i<=15;i++)
{
// calculate the next number in the sequence
nextNumber = firstNumber + secondNumber;
Console.WriteLine(nextNumber);
// make the value of firstNumber the second number
firstNumber = secondNumber;
// make the secondNumber the one just calculated.
13 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
secondNumber= nextNumber;
}
Console.ReadLine();
The program depends on the rule that the next number is the sum of the previous two. After
calculating the next number, we then re-assign:
> the first number with the value of the second one,
> the second one with the value of the new number.
Arrays
Arrays are a group of variables or objects of the same type. When it is necessary to use many
of them, it would be rather tedious to declare several variables such as:
> int a1
> int a2
To declare an array use [ ] after the variable type e.g. int [ ] testScores will declare an array of
integers. If the number of objects is known use int[] testScores =new int[5].
The type of variable used is decimal, even though the number in the array are integers. This is
because the division operator ( / ) will give an integer result if the operands are integers,
which is not what we want in this case.
14 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The statement
total+= scores[i];
In the new dialog - choose text file - rename this file Names.txt
Also of use is to split the string into an array based on a special character, in this case a space.
namespace splitStrings
{
class Program
{
static void Main()
{
string s = "four score and seven";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)
15 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
{
Console.WriteLine(word);
}
Console.ReadLine();
}
}
}
Then, if the items in the file are numbers we need other strategies:
You will need to change the path and filename to one on your system.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace writeTextfile
{
class Program
{
static void Main(string[] args)
{
string[] lines = { "My first line", "My second line", "My third
line", "My last line" };
StreamWriter file = new StreamWriter("c:\myfile.txt");
16 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
foreach (string line in lines)
{
file.WriteLine(line);
}
}
}
> name
> address
You will need to use a symbol other than a space in the file for splitting.
For each line print a statement if the numbers form a Pythagorean triad or not
e.g.
3 4 5 is a Pythagorean triad
17 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
8 15 17
5 12 13
Writing to a file
Essential viewing
It is highly recommended that you watch this series of videos from learn visual studio.
www.learnvisualstudio.net
Note that you may be asked to register to watch the videos. If this occurs please simply enter your
TAFE email address to proceed.
www.dotnetperls.com
18 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Summary
This topic introduces the syntax of the C# language, using visual studio.
> functions
> decisions
> loops
19 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 2 - Object oriented principles
Many computer programming languages are based on procedures.
> They are entirely unstructured. It is difficult to follow valid compiled code.
> It is vulnerable. Changes to code, such as that on a website, can be made while
maintaining its validity. There is no means of detecting such a change.
> They are restricted to the types contained within them. For example, integers and strings.
While object-oriented programming does not eliminate these issues, it reduces their effects.
20 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Object-oriented programming principles
The six principles of object-oriented programming are the focus of this topic.
They are:
1 Abstraction
2 Encapsulation
3 Inheritance
4 Polymorphism
5 Composition
6 Modularity
Abstraction
An abstraction denotes the characteristics of an object that distinguishes it from all other
objects.
In C#, this is done by creating a class. In earlier examples, each program contained at least one
class.
> username
> password
class User
{
public string username;
public string password;
public string email;
Just as integers are types of objects, this has created a new ‘type’ named user. It is often
referred to as a blueprint - it can be used to make many objects.
21 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 11
Create a new project named classExample and enter the following code:
}
class User
{
public string username;
public string password;
public string email;
User myUser = new User() sets aside space in memory for an object of type User.
At this point you need to gain further understanding about what a constructor is and what types of
constructors there are. A good source of this knowledge as relevant to C# is:
http://msdn.microsoft.com/en-us/library/ms173115.aspx
Similarly, the next two lines assign a password and email address.
At this stage, there are no functions for creating a new User object.
22 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
public void User(string n,string p, string e)
{
username = n;
password = p;
email = e;
}
The first creates an empty User - the call is via the new User() statement.
The second allows properties to be added. The call will look like this:
C# will know which one to use since the signatures are different.
Extend this code to create another user myOtherUser and print the properties of it in the same way
as the example.
Encapsulation
This is the principle that the structure of an object and its behaviour can be easily separated.
This can allow the use of an object without knowing how it is constructed.
This is analogous to using an electronic device, such as a mobile phone, without knowing how
the electronics work.
1 The properties,
2 The processes that use those properties. These are also known as methods. In short, this
allows hiding away the properties of an object and only allowing external use of the
processes that use them.
Example
A rectangle has two properties – length and width. The rectangle has two processes getArea
that calculates the area and getPerimeter which calculates the perimeter.
23 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
A rectangle has two properties - length and width. The rectangle has two processes - getArea
that calculates the area and getPerimeter which calculates the perimeter.
class Rectangle
{
private double length;
private double width;
Any property or method that is designated public, is accessible from outside the class. Those
which are declared private are not.
A typical class definition will make properties private and processes or methods public.
This forces outside agencies to use the class in the manner that the developer determines.
It is also common to use methods in classes where properties are private, which set and return
the values of these properties.
e.g. getLength()
{
return length;
}
24 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
setLength( double myLength)
{
Length = myLength;
}
A method with the same name as a class is known as a constructor and is used to make a new
instance of the class or an object.
The toString() method converts a type to string, so it can be printed on the console.
To revisit the principle of encapsulation, a class outside this class, only needs to know how to
create a rectangle not of what it is composed.
This will create a new rectangle - all that is needed is the ‘signature’ of the method.
A signature is the number and type of parameters to pass to the method – in this case 2
double precision numbers.
Extend the Rectangle example to print the area and perimeter of two other rectangles.
Inheritance
This principle is based on the idea that objects are similar. Rather than duplicating code, the
properties of the parent object can be used while also specifying the properties of the child
that are different.
25 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
A square however, has only a length property.
Creating this class based on the previous class will mean that we can avoid re-writing lots of
code.
}
}
This indicates that the new class Square inherits from the base class Rectangle
All the properties and methods for square will be as for Rectangle
Run this code. You will get 0 and 0 for the values of the square since we have no way of
passing parameters to the square as yet.
OOPS! A red underline. This is because the properties of the rectangle are private and can’t be
accessed outside the base class. The parameters could be changed length and width to
public, instead of private, but this would defeat the purpose of making them inaccessible to
other classes.
26 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Use setters and getters for this purpose.
Run this code again - it works, but the problem is that squares have only one parameter so the
area and perimeter is using 0 for the width.
Polymorphism
This principle allows actions or methods to be changed to suit different situations. In practice,
this means changing the definition of a method in an inherited class.
public Square()
{
}
public Square( double a)
{
length = a;
}
27 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Now when the program runs, the correct results are achieved. An advantage of this is when
we have a collection of parent types - shapes.
If we override each correct function Polymorphism will call the correct child method
automatically.
The methods getArea and getPerimeter have been overridden when the child object requires
them. Since the signature of the methods for a square are different, when they are called, the
correct method is used. The advantage here is that if other shapes, with other methods are
used, they too can override these methods.
Add the method diagonal below to the Rectangle class and overload it for the square class.
The purpose is to support multiple variations of the class with different arguments.
Composition
This is the principle that objects can be composed of other objects.
In particular classes may be made up of other classes. The destruction of the outer object does
not destroy the inner objects.
This is implemented in C#, by placing the inner class definition inside another class.
28 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Here is the code for such a program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeckOfCards
{
class Program
{
static void Main(string[] args)
{
class Deck
{
// A deck of 12 cards
Card[] allCards = new Card[12];
29 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
public void deal()
{
// deal 5 cards - listed on the console
int i;
int cardIndex;
Random myRandom = new Random(1);
bool found;
string hand ="";
for (i = 0; i < 5; i++)
{
found = false;
while (!found)
{
// select a card for the hand
cardIndex = myRandom.Next(0, 11);
// Console.WriteLine(cardIndex);
// if it's already in the hand, don't add it
if (!hand.Contains(allCards[cardIndex].getCard()))
{
// add the card to the hand
myHand[i] = allCards[cardIndex];
hand = hand + allCards[cardIndex].getCard();
found = true;
}
}
}
}
public void showHand()
{
int i;
Console.WriteLine("This is my hand");
for (i = 0; i < 5; i++)
{
Console.WriteLine(myHand[i].getCard());
}
Console.ReadLine();
}
class Card
{
private string cardValue;
public Card(string c)
{
cardValue = c;
}
30 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
return cardValue;
}
}
}
}
}
You will need to change the Random value in order that a different set of cards is dealt.
Modularity
This principle refers to the fact that program code is contained in separate modules (classes).
This allows for easier maintenance of code, as problems or bugs can usually be located within
a specific module. Another advantage is the use of the Microsoft base class library. These are
class definitions that Microsoft make available to developers, thus preventing the need to
develop such classes “from scratch”.
Modularity considers how all code run in either in the Main[ ] module or within a class, using
the properties of the class.
Modularity
1 Accelerate, which increases the speed by 10, and brake, which decreases the speed by 10.
31 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Debugging code
It has been shown previously that Visual studio supports debugging of code in several ways.
It may have been clear already that Intellisense is watching what you type and that errors are
reported with red underlining - even before lines of code are complete.
This is true about functions, such as overloaded methods. Intellisense will provide a drop
down menu from which to select.
When you execute a program in the debugger, run time errors will be reported in a pop up.
In order that messages are retained, the same message will appear in the message window
after the pop up is cleared from the screen.
32 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Change the line:
string myString;
to read
string mySring;
This sets off Intellisense as myString is no longer defined. Each occurrence will generate a red
underline.
Note also the red underline – hover over it with the cursor and a list of options will be available to
you.
The pop-up will only suggest an error, not give the details. The debug window will report
errors and the lines on which they occur.
33 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Stepping through a program
Click on the extreme left of the edit window next to line 18 – a red circle appears.
This sets a breakpoint in the program. It can be used to examine the actions of the program
while it is running.
Click the green run button to continue the program. Because the breakpoint is inside the
while loop, it will stop each time it reaches line 18.
Click locals in the error list window at the lower left to see the value of local variables.
Local variable list showing the value of myString “ABCD” at the breakpoint.
34 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is useful in finding logic errors in a program.
Summary
A class is a blueprint for an object. It is created to allow program design to reflect the design
need. Objects are instances from classes.
2 Encapsulation - containing all the information about an object within the class.
Recommended viewing
35 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
http://www.learnvisualstudio.net/free/c-training/
36 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Topic 3 - An object-oriented
programming project
Documentation
Documenting a programming project is a continuous process. At each stage of the project,
documents will support the ideas collected.
Project requirements
Initially, this will consist of several statements listing what the program will need to do. This is
often stated as a description of what the user will be entering and what the output will be.
37 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This is a variation on the mastermind game. The program chooses a four digit number with
no repeated digits and the user has 8 turns in which to guess it.
After each turn, the program responds with a clue about each guess. Each digit in a guess
which occurs in the same position as the program’s number is called a gold, common digits
that occur otherwise are called diamonds.
The 3 is in the correct column (gold) but the 0 is present but not in the correct column
(diamond).
A return of 4 ‘golds’ is then the correct number. The user has a maximum of 8 turns to
get the number correct.
Class diagrams are used to indicate the principles that will occur in the project.
Title
Attributes
Methods
Rectangle
length: double
width: double From Topic 2
getArea()
getPerimeter
38 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Inheritance is shown by connection with an arrow as follows:
Rectangle
length: integer
width: integer
getArea()
getPerimeter
Square
length: double
getArea()
getPerimeter
Aggregation
This is a relationship in which one class is composed of several instances of another class.
For example:
Car Wheel
-memberName -memberName
-memberName -memberName
This indicates that a car object (an instance of the car class) is composed of 1 or more wheel
objects (instances of the wheel class)
Returning to the game in the requirements section above, the following observations are
made.
> A method of the number class will be to calculate what the result is.
> guesses - an int counting how many guesses have been made
> Two instances of numbers the program’s number and the current guess
39 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
> The number class will need members.
> an empty constructor to create a new guess for the user to enter
Game
myNumber
int guesses;
bool over; -string myguess
double result; myNumber();
myNumber answer; myNumber(int type)
myNumber thisGuess; validate();
Play() reply();
This diagram only shows details at the class level. There will be other variables created within
the scope of the named methods.
Modelling solutions
40 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 18
Class diagrams
Internal documentation
Programming standards require that any single program has the following features:
> comments are included to explain to other developers what is being done
Code structure
Visual studio is helpful in that it will indent code as each new scope { } is created.
41 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Appropriate use of commenting
The best programming code makes sparing use of code!
For example:
// this point is reached after the whole file has been read
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Author John Doe
// 6/11/2013
// Version 2.0
// created in C# using Visual studio 2013
namespace GoldDiamonds
{
class Program
{
static void Main(string[] args)
{
// main consists of a single call to the game class
game myGame = new game();
myGame.play();
}
class game
{
myNumber answer = new myNumber(0); // number the user tries to
guess
myNumber myTurn = new myNumber(); // current turn of the user
bool over = false; // flag to indicate whether another turn is
required
int maxGuesses = 8; // fixed number of guessed allowed
int guesses = 0; //
double result; // decimal value of the guess' result
public void play()
{
// main method of the program
// the program ends if 8 guesses are made or the number is
gueesed correctly
while (!over && guesses < maxGuesses)
{
42 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Console.Write("please enter guess " + (guesses + 1)+ " ");
myTurn.myGuess = Console.ReadLine();
if (!myTurn.validate())
{
Console.WriteLine("That guess is not valid");
}
else
{
result = myTurn.reply(answer);
show(result);
guesses++;
if (result == 4 )
{
Console.WriteLine("you win!");
over = true;
}
if (guesses == 8 )
{
over = true;
Console.WriteLine("No the number was " + answer);
}
}
}
Console.ReadLine();
}
public void show(double res)
{
string myResult = res.ToString();
}
class myNumber
{
public string myGuess;
public myNumber ()
{
}
public myNumber(int type)
{
int i;
string myString = "";
string myChar;
int value;
bool found; // flag if a unique digit is chosen.
Random myRandom = new Random();// uses the system Random
Class
for(i=0;i<4;i++)
{
found = false;
// this looks for a digit not already used.
while (!found)
{
value = myRandom.Next(48,57);
myChar = char.ConvertFromUtf32(value);
if (!myString.Contains(myChar))
43 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
{
myString = myString + myChar;
found = true;
}
}
}
myGuess = myString;
}
public bool validate()
{
// validates the user input
bool valid = true; // flag the outcome
int i=0;
string mydigits = "0123456789";
string list ="";
if (!(myGuess.Length == 4)) valid = false;
while (i<4 && valid)
{
// each digit must in mydigits and not be already in
the string
if (mydigits.Contains(myGuess[i] ) &&
!list.Contains(myGuess[i] ))
{
list = list + myGuess[i];
}
else
{
valid = false;
}
i++;
}
return valid;
}
public double reply(myNumber n)
{
// calculate the number of gold and diamonds
string test1 = myGuess;
string test2 = n.myGuess;
int i;
double diamonds = 0;
double golds=0;
// count the golds and diamonds
for(i=0;i<4;i++)
{
if (test1[i] == test2[i]) golds++;
if (test2.Contains(test1[i])) diamonds++;
}
// this loop will count golds as diamonds
// this calculation allows one return value
// e.g. 1.2 is 1 gold and 2 diamonds.
return golds + (diamonds-golds) / 10;
}
}
}
44 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
LEARNING ACTIVITIES ACTIVITY 19
Use of comments - 1
Consider the commenting in the gold and diamonds game. Is there any area where further
comments would help?
Use of comments - 2
namespace commenting
{
class Program
{
static void Main(string[] args)
{
int i;
int j;
int[] myList = { 3, 11, 6 };
for(i=0;i < myList.Length;i++)
{
if (myList[i] < 10 ) Console.WriteLine (myList[i] + " has 1
digit") ;
else
if(myList[i] < 100 ) Console.WriteLine (myList[i] + " has 2
digits");
else Console.Write (myList[i] + " has more than 2 digits");
}
Console.ReadLine();
}
}
}
45 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Testing code
Testing will mean that all requirements of the program are tested.
> that the final feedback is correct – you will need to test for a win and a loss
Testing
Use the guidelines above to completely test the gold and diamonds game.
Can you find any errors in the code - contrary to the requirements?
Creating a solution
To finish these notes, consider a solution created from the requirements statement and the
class diagram provided below.
READINGS RECOMMENDED 1
http://msdn.microsoft.com/en-us/library/kx37x362.aspx
46 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
The word is to be written to the console with the following replacements:
a-@
e-3
i-1
o-0
u-%
Operator Entry
bool over String myString
string temp analyse()
entry myEntry
search()
namespace encode
{
class Program
{
static void Main(string[] args)
{
operation myOperation = new operation();
myOperation.search();
}
class operation
{
bool over = false;
String temp;
entry myEntry = new entry();
47 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
class entry
{
public String text;
case "a":
temp = temp + "@";
break;
case "e":
temp = temp + "3";
break;
case "i":
temp = temp + "1";
break;
case "o":
temp = temp + "0";
break;
case "u":
temp = temp + "%";
break;
default:
temp = temp + text.Substring(i, 1);
break;
}
}
text = temp;
}
}
}
}
}
http://msdn.microsoft.com/en-au/
http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
48 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
This site has references for the C# language
http://www.dofactory.com/reference/csharp-coding-standards.aspx
Summary
Documentation of programs includes two main objectives:
1 Identifying the developer and the context in which the program was written,
Class diagrams are the result of program design. They give developers ideas about what
objects will be used in the program. They show how the objects interact.
49 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Answers to selected activities
Answers are not provided for all activities. Some activities are reflective or are best answered
from your own research or point of view. In these cases you should discuss your answers with
your facilitator/facilitator and other learners wherever possible.
17.1
Animal
Spider Leg
17.2
50 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow
Animal
Insect
Bee
Electric Jug
bool powered
bool boiled
double waterLevel
boil()
fill()
Any area of the program that you need further clarification about needs more comments.
51 | P a g e
ICTPRG406_LG_V1.docm
TAFEnow