De presentatie wordt gedownload. Even geduld aub

De presentatie wordt gedownload. Even geduld aub

Programmeercursus O.O.P. met VISUAL BASIC.NET

Verwante presentaties

Presentatie over: "Programmeercursus O.O.P. met VISUAL BASIC.NET"— Transcript van de presentatie:

1 Programmeercursus O.O.P. met VISUAL BASIC.NET
Les 2 Frans Vanrillaer & John Evans

2 Common Language Runtime
.NET Interne opbouw .NET Framework VB.NET C# VC++.NET J#.NET JScript ……. Common Type System Client-Side Server-Side Mobile-Side .Net Framework Base Class Library Common Language Runtime Windows COM+ Services Windows 2000 / NT / XP

3 .NET Framework Base Class Library Enkele belangrijke Namespace’s
System System.Collections System.Data System.Drawing System.IO System.Reflection System.Security System.Text System.Threading System.Timers System.Web System.Windows.Forms System.Xml Microsoft.CSharp Microsoft.VisualBasic

4 Console Applicatie Automatische Code Imports System Module Module1
We maken het ons gemakkelijk en importeren expliciet de namespace System Noodzakelijk begin Keyword van een Module Naam vd Module Wordt meestal geweizigd Module Module1 Start naam Sub Main( ) Begin Keyword van een Subroutine Console.WriteLine (" " "Hello VB.NET " " " ) Class van System Functie van deze Class End Sub End Module Sluit Subroutine af Sluit Module af Klik ‘F5’ of L-muis klik op:

5 Console Applicatie ? Met Command-Line Argumenten
Pas de code als volgt aan : Module Module1 Sub Main ( ByVal args( ) As String ) Dim s As String For Each s In args Console.WriteLine ( s ) Next End Sub End Module Imports System Hoe laat men deze code RUNNEN We can stretch the first program done above to add the ability of printing the command-line arguments that may be supplied while executing the program. The enhanced program is shown in the slide. There are two ways of supplying command line arguments to a program: - Select Start | Run from menu item following the program name with the arguments that we intend to provide . - Alternatively right click on the project name from the Solution Explorer. Select properties. A property page would be displayed. Click on the configuration properties and select the debugging option from it. Supply the command line arguments. The For Each loop walks through the args( ) array printing each command-line argument in the process. ?

6 Les Overzicht Controle Structuren Proceduren Option Strict
Datatypes Controle Structuren Proceduren Option Strict Type Conversie ByVal/ByRef Meerdere Modules

7 VB.NET DataTypes Value Type Reference Type Andere Char Geheel getal
Boolean Komma getal String Date Object Signed Short Integer Long Unsigned Byte Decimal Floating Point Single Double The data types in VB.NET can be divided into different groups. Integer - Any whole number value can be an integer value. The data types in this group cannot hold fractional values. Integers Data Types are Byte : This is an unsigned data type which means that it can hold only positive data values. Short , Integer , Long : These are signed Integer types and can hold positive as well as negative values. Floating Point Data Types : Floating point data types represent numbers that contain fractional parts. VB.NET supports two types of floating point numbers, Single and Double. Character - The data type in this group can hold a character with a 16-bit Unicode value. Unicode defines fully international character set that can represent all of the characters found in all human languages. It is the unification of dozens of character sets such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul and many more. For this purpose it requires 16 bits to represent each character. VB.NET has two data types to represent character data: Char and String. Boolean - This type can hold logical values. It can have only one of the two possible values, true or false. Decimal - Floating point data types suffer from a precision problem. First of all, they can keep only about 7 digits of accuracy for Single values and 15 digits of accuracy for Double values. To solve this problem, VB.NET has a Decimal data type that can represent any decimal number with up to 28 digits of precision. Date :The date/time data type in VB.NET is Date .This data type can hold dates and/or times. We would discuss String and Object data types later. Short and Char both are of 2 bytes. Short contains binary equivalent of integer stored in it, whereas a Char contains unicode of character stored in it. Reference Type

8 VB.NET DataTypes Detail Gereserveerde
Char Byte Short Integer Long Single Double Decimal Boolean Date 0.0 False 1/1/ :00:00 AM 2 1 4 8 16 Gereserveerde Datatype Initiële waarde Stack plaats Every data type has a strictly defined size and range. This size would remain same irrespective of the platform being used.

9 VB.NET DataTypes Detail Datatype Max waarde Char Byte Short Integer
Long Single Double Decimal Boolean Date +255 +-3,41E+38 +-1.80E+308 +/ True 12/31/ :59:59 PM C S D 1 #

10 VB.NET DataTypes Gebruik Dim i, j As Integer Dim name As String
Dim val As Boolean Dim choice As Char Dim sal As Single Definiëren Dim id As Integer = 10 Dim name As String = "KICIT" Dim val As Boolean = True Dim choice As Char = "y" Dim sal As Single = Definiëren & Initializeren Fout With the statement Dim i As Integer, 4 bytes would be reserved for i on stack. If we are declaring one variable then we can initialize it there only . Ex Dim j As integer =1. With this statement 4 bytes would be reserved on stack for j and value one would be stored in it. However such initialization will not work if we are declaring more than one variable at a time. The keyword Const is used for defining constant variables. It is necessary to initialize a constant variable at the time of declaration. Once a value is assigned to these variables it cannot change. If two integers are to be initialized it has to be done in 2 separate statements. Const m As Integer = 10 Const pi As Single = 3.14 Const n As String = "Hi" Const ch As Char = "y" Constanten Dim i = 10, j = 10 As Integer Dim b As Boolean = True Dim m, k As Integer = 10 Const k As Integer OK? Juist Fout Fout

11 VB.NET DataType: Boolean Nota: Boolean is True of False.
True in NIET 1 en False NIET 0 Imports System Module Module1 Sub Main( ) Dim a As Boolean = True Dim b As Boolean = False Console.WriteLine ( "A = " & a ) Console.WriteLine ( "Result = " & ( 4 < 3 ) ) Console.ReadLine End Sub End Module A=True The Boolean data type has only two values True or False. Unlike C, in VB.NET True is not 1 and False is not 0. Result=False

12 DataTypes: Operatoren
VB.NET DataTypes: Operatoren Reken operatoren : , -, *, /, ^, \, Mod Relatie operatoren : =, <>, <, >, <=, >= Logische operatoren Bitwise And, Or, Xor, Not, AndAlso, OrAlso Samenvoegen : =, +=, -=, /=, *=, \= The Arithmetic operators may be applied to any of the numerical data types like Integer, Floating-point, and Decimal. The evaluation of any expression will always result in a value that can be used to represent the most precise operand. For example, if both operands of a multiply are Integer, the result will be Integer. However, if one operand is an Integer and the other operand is a Double, the result will be a Double because it can represent more digits of precision. Relational Operators : VB.NET has six operators for making comparisons. Each operator returns either the Boolean value True or False. Logical Operators : You can combine Boolean values (conditions) by using the binary logical operators And, Or, and Xor. Bitwise Operators : These operators are similar to logical operators with one exception that the logical operators require that the operands in the expression are Boolean values. Unlike this the bitwise operators operate upon numeric values and would yield numeric values. = is used for assignment as well as comparison. Which is used is decided by context.

13 VB.NET Oefening: Console I/O
Open een nieuwe console applicatie: console01 Dim n As String Dim a As Integer Dim s As Single Console.WriteLine ( “Geef naam, leeftijd en salaris " ) n = Console.ReadLine( ) a = CInt ( Console.ReadLine( ) ) s = CSng ( Console.ReadLine( ) ) Console.WriteLine ( _ "Naam: { 0 } Leeftijd: { 1 } Salaris: { 2 }", n, a, s ) Converteren Plaatshouder

14 VB.NET Converteren Placeholders
Eenvoudige placeholders: {n}, waar n 0,1,2, ….., Controle op Lengte: {n,w}, w is de breedte. {0,12} of {0,-8}        Positief voor rechts uitlijnen,        Negatief voor links uitlijnen. Soort value: {n,S}: S hoe de inhoud getoond moet worden. {0,8:f3} C,c    Currency formaat (instelling) -afronding D,d    Decimaal E,e    Scientific (exponential) F,f    Fixed point (vb. F2) -afronding G,g    General (instelling) N,n    Getal formaat (vb. N1) -afronding X,x    Hexadecimaal Breedte en Format string: {n,w:S} Placeholders CChar CByte CShort CInt CLng CSng CDbl CDec CBool Cdate Cobj CStr Char Byte Short Integer Long Single Double Decimal Boolean Date Object String

15 DataTypes: Beveiliging
VB.NET DataTypes: Beveiliging ? Dim s As Short = 400 Dim s As Short = 32768S Dim s1 As Short = 40 Dim s2 As Short = 3276 Dim a As Integer a = s1 * s2 ?

16 VB.NET Data Type: Char Het primitive data type Char vertegenwoordigt een individueel karakter. Dim ch1 As char = “a”C Dim n As Integer = AscW(ch1) n += 1 ch1 = ChrW(n) Speciale ascii codes: Constante die staan in Microsoft.VisualBasic namespace Naam Waarde VB naam Single quote &H27   Double quote &H22   Backslash &H5C   Null &H0 vbNullChar Alert &H7   Backspace &H8 vbBack Form feed &HC vbFormFeed Line feed &HA vbLf Naam Waarde VB naam Carriage return &HD vbCr New Line &HD + &HA VbLfCr of VbNewLine Horizontal tab &H vbTab Vertical tab &HB vbVerticalTab

17 VB.NET String class is een OBJECT dat eenmaal het gecreëerd is, NIET meer kan verandert worden. Elke verandering creëert een NIEUW string-object !!! String Methods en Properties Individuele karakters uit een string kunnen via Chars(index) benaderd worden. String.Length String.ToUpper String.ToLower String.Substring() String.IndexOf() String.Chars() Dim str As String = "goodbye“ str = str.ToUpper() str = str.ToLower() Dim l As Integer = str.Length Dim substring As String = str.Substring(4, 3) Dim n1 As Integer = str.IndexOf("bye") Dim n2 As Integer = str.IndexOf("boo") Dim s As Integer = Asc(str.Chars(2))

18 VB.NET StringBuilder class Imports System.Text.StringBuilder
Dim myBuilder As Text.StringBuilder = New Text.StringBuilder(10000) Dim rng As Random = New Random Dim bgB As Double = Now.Ticks For i As Integer = 1 To 10000 Dim c As Char = Convert.ToChar(rng.Next(65, 90)) myBuilder.Append(c) Next Dim edB As Double = Now.Ticks Disp("Ticks bij stringBuider: " + Convert.ToString(edB - bgB))

19 VB.NET Stuctured Data Types Array Enumertion Dim balance(4) As Decimal
{100, 200, 300, 400, 250} Dim balance(,) As Decimal = _ {{100, 200, 300, 400, 250} , _ {100, 200, 300, 400, 250} , _ {100, 200, 300, 400, 250} } Enum Kaarten Aas = 1 Twee = 2 ….. Boer = 11 Dame = 12 Heer = 13 End Enum Structure Structure Persoon Naam As String Vnaam As String Gdat As Date End Structure

20 VB.NET Voorbeeld Module Module1 Enum PColor rood groen blauw End Enum
Structure PiCoord Public x As Single Public y As Single Public flags() As Byte Public color As PColor End Structure Structure Rectangle Public tLeft As PCoord Public tRight As PCoord Public bLeft As PCoord Public bRight As PCoord Public fillColor As PColor Sub Main() Dim r As Rectangle r.tLeft.x = 100 r.tLeft.y = 100 r.tLeft.color = PColor.groen r.tRight.x = 300 r.tRight.y = 100 r.tRight.color = PColor.groen r.bLeft.x = 100 r.bLeft.y = 300 r.bLeft.color = PColor.groen r.bRight.x = 300 r.bRight.y = 300 r.bRight.color = PColor.groen WriteLine(“Waarde r.tLeft.x = {0} ", r.tLeft.x) WriteLine(“Waarde r.tLeft.y = {0} ", r.tLeft.y) WriteLine(“Duw <Enter> =Stop") ReadLine() End Sub End Module

21 VB.NET Controle Structuren Beslissing Struc. Herhalings Struc. IF
Select For While Do If a>b Then blablablabla End If For i = 0 To 100 blablablabla Next Do Until a>b blablablabla Loop Select Case a case 1 blablablabla case Else doedoedoe End Case While a>b blablablabla End While Do blablablabla Loop While a<b

22 Beslissings Structuur
VB.NET Beslissings Structuur IF IIF Dim i As Integer Dim res As String i = CInt ( Console.ReadLine( ) ) res = IIf ( i Mod 2 = 0, "Even", “Oneven" ) Console.WriteLine ( res ) If Conditie Then ... End If If Conditie Then ... Else End If Evaluated Cond1 Cond2 True False Evaluated Not Eval. If age > 18 AndAlso no < 11 Then End If IIf is known as the Immediate Iff function. If the condition is satisfied i.e i Mod 2 is equal to 0 then "Even" would be assigned to res else res would hold the value “Oneven". VB.NET also provides two logical operators, AndAlso and OrElse that can be used to help evaluate expressions as efficiently as possible. For example, when evaluating the expression: age > 18 And no < 11 If the value of age is less than 18, there is no need to evaluate the second expression. If we use And then bothe expressions would get evaluated. Thus even if the first condition is false the second would still get evaluated to determine the result. The AndAlso operator is used to prohibit the evaluation of the second condition if the result of the expression is known after evaluating the first operand. If the value of age is less than 18, the evaluation of the expression stops and the operator returns False. Similar is the case with the OrElse operator. However in this case if the first condition is true, the second condition will not be evaluated and the operator returns True. If Conditie1 Then ... ElseIf Conditie2 Else End If Cond1 Cond2 True False Not Eval. Evaluated If age > 18 OrAlso no < 11 Then End If

23 Beslissings Structuur
VB.NET Select Case Beslissings Structuur Select Case dagNr Case 0 dag = “Zondag" Case 1 dag = “Mon" Case 2 dag = “Tue" Case 3 dag = “Wed" End Select Select Case id Case 1, 5 To 9 grp = "Grp A" Case 10 To 15 grp = "Grp B" Case 16 grp = "Grp C" End Select Select Case stad Case “Leuven", “Tienen" state = “V-Br" Case “Namur" state = “NM" Case Else state = “Onbekend" End Select Another type of decision construct is the Select statement. Select Case expression Case case-clause statement(s) Case case-clause statement(s) Case Else statement(s) End Select The statement must begin with the keyword Select Case. The expression is evaluated, and based on its value, the statements in one Case may be executed. The square brackets indicate there may be additional Case statements besides the required one. There can optionally be a Case Else, which is executed if no case matches the value of the expression. Finally, the Select Case is terminated by the keyword End Select.

24 VB.NET Herhalings Structuur For … Next While For i = 0 To 10
Console.WriteLine ( i ) Next i = 0 While i <= 10 Console.WriteLine ( i ) i = i + 1 End While For i = 10 To 0 Step –1 Console.WriteLine( i ) Next Step keyword is used to determine the value by which i is to be incremented each time in a For loop. By default the value of Step is taken as 1. Dim s As String = "y" While s = "y" s = Console.ReadLine( ) End While For I As Integer = 10 To 0 Step –1 Console.WriteLine( i ) Next

25 VB.NET Herhalings Structuur Do … Loop i = 0 Do While i <= 10
Console.WriteLine ( i ) i += 1 Loop i = 15 Do Until i = 10 Console.WriteLine ( i ) i = i + 1 Loop i = 10 Do Console.WriteLine ( i ) i -= 1 Loop While i <= 2 i = 15 Do Console.WriteLine ( i ) i = i + 1 Loop Until i = 10

26 Herhalings Structuren
VB.NET Herhalings Structuren Vroegtijdig Verlaten DO While For i = 0 Do While i <= 10 C.W ( i ) If i = 5 then Exit Do End If i = i + 1 Loop While i <= 10 C.W ( i ) If i = 5 then Exit While End If i = i + 1 End While For i = 0 To 10 C.W ( i ) If i = 5 then Exit For End If Next Loops can be exited prematurely using the Exit statement. The Exit statement can be used with any of the Do, For or While loops

27 VB.NET Procedures Subroutine Function Sub Display( ) C.W ( "1.Add" )
C.W ( "2.Del" ) C.W ( "3.Disp" ) C.W ( "4.Exit" ) End Sub Function fact ( val As Integer ) As Integer Dim f As Integer = 1 Dim i As Integer For i = 1 To val f = f * i Next Return f End Function Geeft NIETS terug Geeft waarde terug

28 VB.NET Option Strict default Beter Option Strict Off Option strict On
Voorkomt RunTime fouten! Option Strict Off Dim i As Integer = 10 Dim f As Single Dim g As Single = 6.82 f = i Console.WriteLine ( f ) i = g Console.WriteLine ( i ) Wat indien Strict On ? Using the option Option Strict that we can indicate the level of type checking that should be used. By default the Option Strict is off. When off it lets us assign the value of a string to an integer variable. VB.NET performs an implicit conversion in this case. However with Option Strict on, VB.NET will not perform implicit conversions instead it will give an error saying "Option Strict disallows implicit conversions from String to Integer" If Option Strict is on, the compiler will not necessarily generate error messages on all data type mismatches. For example, on numeric assignments, VB.NET is primarily concerned about loss of precision. Dim f As Single Dim i As Integer ' if no loss of precision occurs, "obvious" implicit conversions are allowed f = i ' if loss of precision occurs, all implicit conversions are disallowed i =f Conversions where there is no loss of precision are allowed even with Option Strict On. On assigning an Integer value to a Single since there is no loss of precision this conversion is allowed. The Boolean data type is incompatible with all other data types. On assigning a Float to an Integer appropriate rounding off or truncation takes place. Same is true with CInt.

29 VB.NET Call ByVal ByRef default Module Module1 Sub Main()
Dim num As Integer = 1 funcv(num) controle.WriteLine(“num = {0}”, num) funcr(num) End Sub Sub funcv(num As Integer) num += 10 Controle.WriteLine( _ “num = {0}”, num) End Sub Sub funcr(ByRef num As Integer)

30 VB.NET Voorbeeld Module Module1 c1 = c2 Structure Card c2.naam = "Joe“
Public naam As String Public pcid As Integer End Structure Sub Main() Dim i As Integer = 7, j As Integer = 3 WriteLine(“Waarde i is {0} en j is {1} ", i, j) i = j j = 2 WriteLine(“Nieuw i is {0} en j is {1} ", i, j) Dim c1 As Card, c2 As Card = "Video card“ c1.pcid = 0 = "Audio card“ c2.pcid = 6 WriteLine( _ “Waarde c1.naam is {0} en c1.pcid is {1} ", _ c1.naam, c1.pcid) “Nieuw c2.naam is {0} an c2.pcid is {1} ", _ c2.naam, c2.pcid) c1 = c2 c2.naam = "Joe“ c2.pcid = 123 WriteLine(“Waarde c1.naam is {0} en c1.pcid is {1} ", _ c1.naam, c1.pcid) WriteLine(“Nieuw c2.naam is {0} en c2.pcid is {1} ", _ c2.naam, c2.pcid) Dim a1() As Integer = {1, 2, 3, 4, 5} Dim a2() As Integer = {6, 7, 8, 9, 0} WriteLine(“Waarde a1(3) is {0} en a2(3) is {1} ", _ a1(3), a2(3)) a1 = a2 a1(3) = -1 WriteLine(“Nieuw a1(3) is {0} en a2(3) is {1} ", _ WriteLine(“Duw <Enter> = Stop") ReadLine() End Sub End Module

31 VB.NET Multiple Modules Scope Module Module1 Dim i As Integer = 20
Sub Main( ) Dim i As Integer = 10 Console.WriteLine ( i ) Console.WriteLine ( Module1.i ) End Sub End Module The slide shows how to call subroutines from different modules. If a function or a subroutine is in module2 and we want to call it in another module, say module1, then within module1 write module2.subroutinename( ) The slide shows how to refer a global variable within a function. If within main( ) we want to refer to the global i then the way to do so is Module1.I If we mention just i then what we are referring to is the most local copy of i.

32 VB.NET Oefenen ! MinMax.vb
Maak een programma dat voor alle data types, hun min. en max. waarde op het scherm zet. Nota: gebruik de MinValue- en MaxValue propertie WoordGetal.vb Een getal wordt als command lijn argument mee gegeven. Schrijf een programma dat dit getal in woorden toont. Nota: 256 als twee, vijf, zes Oplopend.vb Schrijf een programma dat vier cijfers accepteert en deze dan in oplopende volgorde toont.

33 VB.NET Oefenen ! SomEven Schrijf een console applicatie, die de som maakt van even getallen tussen 1 en Gebruik een For/Next loop Declareer de variabelen sum en count. Vraagje Met welk statement kan men een While loop verlaten? Tafels Maak een console applicatie, die de tafel van 1 to 5 toont. De tafels staan naast elkaar, netjes geformateerd. Pythagoras Driehoeken Maak een console applicatie, die de afmetingen(zijde1, zijde2, schuineZ) van alle driehoeken toont, die voldoen aan volgende formule: het kwadraat van de schuine zijde is gelijk aan de som van de kwadraten van de 2 andere zijden, bij komende voorwaarde de lengte van de schuine zijde mag niet groter zijn dan 30.

34 VB.NET Oefening Enigma Deze appl. versleutelt een gegeven woord of zin en ontsleutelt ze. In de gecodeerde string zit de sleutel vervat om hem te decoderen: MIDDENBLOK: het gegeven woord of zin VERHOGINGSFACTOR: de ascicode van elk karakter van het middenblok wordt verhoogd met een randgetal tussen 16 en 35 BLOK1: de gecodeerde string wordt vooraf gegaan door een blok van 10 random karakters indien 5de karakter BLOK1 = X dan zit de verhogingsfactor vervat in de eerste 2 karakters van BLOK indien 5de karakter BLOK1 = B dan zit de verhogingsfactor vervat in de eerste 2 karakters van BLOK2 BLOK2: de gecodeerde string wordt achteraf gegaan door een blok van 10 random karakters REVERSE: indien laatste karakter van BLOK2 = ascicode(X) + verhogingsfactor dan MIDDENBLOK is gereversed REVERSE: indien laatste karakter van BLOK2 = ascicode(B) + verhogingsfactor dan MIDDENBLOK is niet gereversed

35 VB.NET Volgende Les OOP UML Classes Objecten

Download ppt "Programmeercursus O.O.P. met VISUAL BASIC.NET"

Verwante presentaties

Ads door Google