The document outlines procedures in Visual Basic, including sub procedures, function procedures, methods, argument promotion, value types vs. reference types, and passing arguments by value vs. reference. It provides examples of each type of procedure and discusses key concepts like scope, overloading, and recursion. Visual Basic procedures allow programmers to organize and structure their code into logical, reusable units.
maXbox Starter 43 Work with Code Metrics ISO StandardMax Kleiner
Today we step through optimize your code with metrics and some style guide conventions. You cannot improve what you don’t measure and what you don’t measure, you cannot prove. A tool can be great for code quality but also provides a mechanism for extending your functions and quality with checks and tests.
maXbox Starter 43 Work with Code Metrics ISO StandardMax Kleiner
Today we step through optimize your code with metrics and some style guide conventions. You cannot improve what you don’t measure and what you don’t measure, you cannot prove. A tool can be great for code quality but also provides a mechanism for extending your functions and quality with checks and tests.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This follow up post on the subject of Artificial Intelligence focuses on Expert Systems and the role of traditional experts in their design and development. It explores four main themes:
What do we mean by Expert?
How do experts work?
Expert Systems Application Domains, and
Features of rule based Expert (KB) Systems
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This follow up post on the subject of Artificial Intelligence focuses on Expert Systems and the role of traditional experts in their design and development. It explores four main themes:
What do we mean by Expert?
How do experts work?
Expert Systems Application Domains, and
Features of rule based Expert (KB) Systems
Dynamic Function Call in PI Sheet (XStep)Ankit Sharma
Using of Dynamic Function Call in PI Sheet (XStep).
Use
You can use this function to call certain SAP functions from within the PI sheet or perform certain calculations and checks in the PI sheet. ABAP function calls that have been created for the corresponding use are used for the function call.
Prerequisites
The function module to be called must exist and be active in the Function Builder (ABAP Development Workbench).
Features
The SAP system contains a number of predefined function modules that you can use in function calls. You can also create your own function modules.
PT1420 Decision Structures in Pseudocode and Visual Basic .docxamrit47
PT1420: Decision Structures in Pseudocode and Visual Basic
Page 1
This lab requires you to think about the steps that take place in a program by writing
pseudocode. Read the following program prior to completing the lab.
Career Tech Placement is hiring employees for placement at technology firms across the
city. Prior to granting an interview, the company has a 100-point test that is used to
determine if the candidate should be interviewed. Depending on the candidate’s score,
he or she will be placed in 1 of 4 categories for possible employment and flagging for an
interview:
Score Employment Category Interview Possibility
85 or above Definite Yes
70 – 84 Likely Yes
60 – 69 Maybe Yes
59 or below No No
Career Tech Placement has asked you to write a program that will allow the company to
enter a test score and then set the employment category and the interview possibility
variables based on the chart above.
Given the major task involved in this program, you decide your program should have three
variables and three modules:
Variable Name Purpose
Declare Integer testScore = 0 Stores the test score of the candidate.
Declare String category = “ “ Stores Definite, Likely, Maybe, or No
Declare String interview = “ “ Stores Yes or No
PT1420: Decision Structures in Pseudocode and Visual Basic
Page 2
Module Name Purpose
Module getScore() Allows the user to enter the test score
Module employCat() Determines the employment category
Module interviewPoss() This module will determine if a day off should
be awarded.
Module displayInfo() Displays the testScore, category, and interview
variables.
Step 1: Complete the pseudocode by writing the missing lines. When writing your modules and
making calls, be sure to pass necessary variables as arguments and accept them as reference
parameters if they need to be modified in the module (Reference: Testing a Series of
Conditions, page 138 from your textbook, Starting Out with Programming Logic & Design.).
Main Module()
//Declare variables on the next 3 lines
//Make Module calls and pass necessary variables on the next 4 lines
End Main
Module getScore(Integer Ref testScore)
//Ask the user to enter a test score
End Module
Module employCat(Integer testScore, String Ref category)
//Determine what employment category they are in based on their test score
//Similar to if the score is less than 60, then category is “No”
PT1420: Decision Structures in Pseudocode and Visual Basic
...
import java.util.Scanner;Henry Cutler ID 1234 7202.docxwilcockiris
import java.util.Scanner;
/*
Henry Cutler ID 1234 7/20/2015
Assignment #5, 3 features in 1 program
Solution
for Assignment#5 COP2800
Pseudocode:
Program has three features, all in a single program that are user selectable.
Prompt with options and get user choice inside a while statement ( true )
If 1 is entered:
Using a while and for loop, print out the ASCII table from ! to ~.
If 2 is entered:
Prompt the user for number of times to flip for head or tails using the random method. Count number of each and when the request times are done, print out the results.
If 3 is entered:
Prompt the user for a strings and print back the count of vowels and letters
Any other input entered program will exit using a break statement, otherwise loops back to prompt user for feature selection.
*/
public class Module5 {
public static void main(String[] args) {
// prompt the user
System.out.println("Welcome to Henry\'s 3 in 1 Programming Assignment for Module 5\n");
// create Scanner Object
Scanner input = new Scanner(System.in);
// loop until break
while(true){
// new lines for readability
System.out.print("\n");
// Prompt user for choices
System.out.print("Enter 1 for ASCII Table \nEnter 2 for Heads or Tails\nEnter 3 for Count Vowels & Letters\nAny other input will exit");
int choice = input.nextInt();
// Consume newline left-over
input.nextLine();
// first feature
if(choice == 1){
// start value is !
int value = (int) '!';
// newline for formating
System.out.println("You Selected ASCII Table!\n");
// start at ~ which is 33 decimal
while( value <= '~')
{
// print out 20 in a line
for( int count = 0; count < 20; count ++ ){
if( value <= '~'){
// print single value
System.out.print( (char) value++ );
}
else {
// break when we are at last char to print
break;
}
}
// New line every 10
System.out.print("\n");
}
// New line at exit
System.out.print("\n");
}
else if(choice == 2){
// Prompt user
System.out.println("You Selected Head or Tails!");
System.out.println("\nHow many flips would you like to try?");
// get value
int count = input.nextInt();
// clear
input.nextLine();
int headCount = 0;
int tailCount = 0;
// run for a count provided by user
for (int i = 0; i < count; i++) {
// get random number
if (Math.random() > 0.5){
// increment heads
headCount++;
}
else {
// increment tails
tailCount++;
}
}
System.out.println("Head count: " + headCount + " tail count: " + tailCount);
}
else if(choice == 3){
// Prompt user
Sys.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
Week 2 iLab TCO 2 — Given a simple problem, design a solutio.docxmelbruce90096
Week 2 iLab
TCO 2 — Given a simple problem, design a solution algorithm that uses arithmetic expressions and built-in functions.
Scenario
Your goal is to solve the following simple programming exercise. You have been contracted by a local antique store to design an algorithm determining the total purchases and sales tax. According to the store owner, the user will need to see the subtotal, the sales tax amount, and the total purchase amount. A customer is purchasing four items from the antique store. Design an algorithm where the user will enter the price of each of the four items. The algorithm will determine the subtotal, the sales tax, and the total purchase amount. Assume the sales tax is 7%.
Be sure to think about the logic and design first (input-process-output (IPO) chart, flowchart, and pseudocode). Display all output using currency formatting.
Advanced (optional): Use a constant for the 7% sales tax.
Rubric
Point distribution for this activity:
iLab Activity
Document
Points possible
Points received
Variable list
10
IPO chart
10
Flowchart
10
Pseudocode/C# code
10
Desk-check
10
Total Points
50
Name:_________________
(1) Variable List With Data Type
List all the variables you will use (use valid variable names). Indicate whether the data type is string, integer, or double, and so on.
(2) IPO Model
List the inputs, any processes, calculations, and outputs. Use the same valid variable names you used in Step 1.
Inputs
Process (calculations)
Outputs
(3) Flowchart
Use MS Visio to create a flowchart. Paste the flowchart here, or attach as separate document. Use the same valid variable names you used in Step 1.
(4) Pseudocode or C# Code
Describe your solution using pseudocode or actual C# code. Use the same valid variable names you selected in Step 1.
(5) Desk-Check
Desk-check your solution by selecting appropriate test data.
Test data: List the values for your test data.
Expected output: What is the expected output of your program?
Step
Variables (write variable names in first line below)
Output
Enter step numbers
1
2
3
Week 2 Activity—Game Seating Charges
TCO 2—Given a simple problem, design a solution algorithm that uses arithmetic expressions and built-in functions.
Assignment
Your goal is to solve the following simple programming exercise. You have been contracted by a local stadium to design an algorithm determining the total seating charges for any game held at the stadium. Lower-level seats cost $25 per seat, mid-level seats cost $15 per seat, and upper-level seats cost $10 per seat. The algorithm should ask the user for the number of seats being purchased in each seating level. Then, the algorithm will determine the total for each level and a grand total for the enti.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
06 procedures
1. Chapter 6 - Procedures Outline 6.1 Introduction 6.2 Modules, Classes and Procedures 6.3 Sub Procedures 6.4 Function Procedures 6.5 Methods 6.6 Argument Promotion 6.7 Option Strict and Data Type Conversions 6.8 Value Types and Reference Types 6.9 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 6.10 Duration of Identifiers 6.11 Scope Rules 6.12 Random-Number Generation 6.13 Example: Game of Chance 6.14 Recursion 6.15 Example Using Recursion: The Fibonacci Series 6.16 Recursion vs. Iteration
6. 6.2 Modules, Classes and Procedures Fig. 6.1 Hierarchical boss procedure/worker procedure relationship. Boss Worker1 Worker2 Worker3 Worker4 Worker5
7.
8.
9. Payment.vb Program Output 1 ' Fig. 6.2: Payment.vb 2 ' Sub procedure that prints payment information. 3 4 Module modPayment 5 6 Sub Main() 7 8 ' call Sub procedure PrintPay 4 times 9 PrintPay( 40 , 10.5 ) 10 PrintPay( 38 , 21.75 ) 11 PrintPay( 20 , 13 ) 12 PrintPay( 50 , 14 ) 13 14 Console.ReadLine() ' prevent window from closing 15 End Sub ' Main 16 17 ' print amount of money earned in command window 18 Sub PrintPay( ByVal hours As Double , ByVal wage As Decimal ) 19 20 ' pay = hours * wage 21 Console.WriteLine( "The payment is {0:C}" , hours * wage) 22 End Sub ' PrintPay 23 24 End Module ' modPayment The payment is $420.00 The payment is $826.50 The payment is $260.00 The payment is $700.00 PrintPay executes when it is invoked by Main PrintPay receives the values of each argument and stores them in the parameters variables hours and wage Notice that PrintPay appears within modPayment . All procedures must be defined inside a module or a class
10.
11.
12. SquareInteger.vb 1 ' Fig. 6.3: SquareInteger.vb 2 ' Function procedure to square a number. 3 4 Module modSquareInteger 5 6 Sub Main() 7 Dim i As Integer ' counter 8 9 Console.WriteLine( "Number" & vbTab & "Square" & vbCrLf ) 10 11 ' square numbers from 1 to 10 12 For i = 1 To 10 13 Console.WriteLine(i & vbTab & Square(i)) 14 Next 15 16 End Sub ' Main 17 18 ' Function Square is executed 19 ' only when the function is explicitly called. 20 Function Square( ByVal y As Integer ) As Integer 21 Return y ^ 2 22 End Function ' Square 23 24 End Module ' modSquareInteger The For structure displays the results of squaring the Integer s from 1-10 Square is invoked with the expression Square(i) The Return statement terminates execution of the procedure and returns the result of y ^ 2
16. Maximum.vb 1 ' Fig. 6.4: Maximum.vb 2 ' Program finds the maximum of three numbers input. 3 4 Public Class FrmMaximum 5 Inherits System.Windows.Forms.Form 6 7 ' prompts for three inputs 8 Friend WithEvents lblOne As System.Windows.Forms.Label 9 Friend WithEvents lblTwo As System.Windows.Forms.Label 10 Friend WithEvents lblThree As System.Windows.Forms.Label 11 12 ' displays result 13 Friend WithEvents lblMaximum As System.Windows.Forms.Label 14 15 ' read three numbers 16 Friend WithEvents txtFirst As System.Windows.Forms.TextBox 17 Friend WithEvents txtSecond As System.Windows.Forms.TextBox 18 Friend WithEvents txtThird As System.Windows.Forms.TextBox 19 20 ' reads inputs and calculate results 21 Friend WithEvents cmdMaximum As System.Windows.Forms.Button 22 23 ' Visual Studio .NET generated code 24 25 ' obtain values in each text box, call procedure Maximum 26 Private Sub cmdMaximum_Click( ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdMaximum.Click 28 These are declarations of all the controls used in the GUI. Create these components visually, using the Toolbox Remember that all forms inherit from class System.Windows.Forms.Form Event handler cmdMaximum_Click Handles the event in which Button cmdMaximum is clicked
17. Maximum.vb Program Output 29 Dim value1, value2, value3 As Double 30 31 value1 = txtFirst.Text 32 value2 = txtSecond.Text 33 value3 = txtThird.Text 34 35 lblMaximum.Text = Maximum(value1, value2, value3) 36 End Sub ' cmdMaximum_Click 37 38 ' find maximum of three parameter values 39 Function Maximum( ByVal valueOne As Double , _ 40 ByVal valueTwo As Double , ByVal valueThree As Double ) 41 42 Return Math.Max(Math.Max(valueOne, valueTwo), valueThree) 43 End Function ' Maximum 44 45 End Class ' FrmMaximum The values in the three TextBox es are retrieved using the Text property Call to methods defined in the class that contains the method call need only specify the method name Call to methods that are defined in a class in the FCL must include the class name and the dot ( . ) operator
18. 6.5 Methods Fig. 6.5 Parameter Info feature of the Visual Studio .NET IDE. Parameter Info window
19. 6.5 Methods Fig. 6.6 IntelliSense feature of the Visual Studio .NET IDE.
25. 6.7 Option Strict and Data-Type Conversions Fig. 6.9 Property Pages dialog with Option Strict set to On.
26.
27. 6.8 Value Types and Reference Types Fig. 6.10 Visual Basic primitive data types.
28. 6.8 Value Types and Reference Types Fig. 6.11 Literals with type characters.
29.
30. ByRefTest.vb 1 ' Fig. 6.12: ByRefTest.vb 2 ' Demonstrates passing by reference. 3 4 Module modByRefTest 5 6 ' squares three values ByVal and ByRef, displays results 7 Sub Main() 8 Dim number1 As Integer = 2 9 10 Console.WriteLine ( "Passing a value-type argument by value:" ) 11 Console.WriteLine( "Before calling SquareByValue, " & _ 12 "number1 is {0}" , number1) 13 SquareByValue(number1) ' passes number1 by value 14 Console.WriteLine( "After returning from SquareByValue, " & _ 15 "number1 is {0}" & vbCrLf , number1) 16 17 Dim number2 As Integer = 2 18 19 Console.WriteLine ( "Passing a value-type argument" & _ 20 " by reference:" ) 21 Console.WriteLine( "Before calling SquareByReference, " & _ 22 "number2 is {0}" , number2) 23 SquareByReference(number2) ' passes number2 by reference 24 Console.WriteLine( "After returning from " & _ 25 "SquareByReference, number2 is {0}" & vbCrLf , number2) 26 27 Dim number3 As Integer = 2 28 When number1 is passed, a copy of the value is passed to the procedure A reference to the value stored in number2 is being passed
31. ByRefTest.vb 29 Console.WriteLine ( "Passing a value-type argument " & _ 30 " by reference, but in parentheses:" ) 31 Console.WriteLine( "Before calling SquareByReference " & _ 32 "using parentheses, number3 is {0}" , number3) 33 SquareByReference((number3)) ' passes number3 by value 34 Console.WriteLine( "After returning from " & _ 35 "SquareByReference, number3 is {0}" , number3) 36 37 End Sub ' Main 38 39 ' squares number by value (note ByVal keyword) 40 Sub SquareByValue( ByVal number As Integer ) 41 Console.WriteLine( "After entering SquareByValue, " & _ 42 "number is {0}" , number) 43 number *= number 44 Console.WriteLine( "Before exiting SquareByValue, " & _ 45 "number is {0}" , number) 46 End Sub ' SquareByValue 47 48 ' squares number by reference (note ByRef keyword) 49 Sub SquareByReference( ByRef number As Integer ) 50 Console.WriteLine( "After entering SquareByReference" & _ 51 ", number is {0}" , number) 52 number *= number 53 Console.WriteLine( "Before exiting SquareByReference" & _ 54 ", number is {0}" , number) 55 End Sub ' SquareByReference 56 57 End Module ' modByRefTest ByVal indicates that value-type arguments should be passed by value ByRef gives direct access to the value stored in the original variable Enclosing arguments in parenthesis forces pass-by-value
32. Program Output Passing a value-type argument by value: Before calling SquareByValue, number1 is 2 After entering SquareByValue, number is 2 Before exiting SquareByValue, number is 4 After returning from SquareByValue, number1 is 2 Passing a value-type argument by reference: Before calling SquareByReference, number2 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses: Before calling SquareByReference using parentheses, number3 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number3 is 2
33.
34.
35. Scoping.vb 1 ' Fig. 6.13: Scoping.vb 2 ' Demonstrates scope rules and instance variables. 3 4 Public Class FrmScoping 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblOutput As System.Windows.Forms.Label 8 9 ' Windows Form Designer generated code 10 11 ' instance variable can be used anywhere in class 12 Dim value As Integer = 1 13 14 ' demonstrates class scope and block scope 15 Private Sub FrmScoping_Load( ByVal sender As System.Object, _ 16 ByVal e As System.EventArgs) Handles MyBase .Load 17 18 ' variable local to FrmScoping_Load hides instance variable 19 Dim value As Integer = 5 20 21 lblOutput.Text = "local variable value in" & _ 22 " FrmScoping_Load is " & value 23 24 MethodA() ' MethodA has automatic local value 25 MethodB() ' MethodB uses instance variable value 26 MethodA() ' MethodA creates new automatic local value 27 MethodB() ' instance variable value retains its value 28 29 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 30 "value in CScoping_Load is " & value 31 End Sub ' FrmScoping_Load 32 33 ' automatic local variable value hides instance variable 34 Sub MethodA() 35 Dim value As Integer = 25 ' initialized after each call This variable is hidden in any procedure that declares a variable named value Automatic variable value is destroyed when MethodA terminates None of the method calls modifies this variable – both methods refer to variables in other scopes
36. Scoping.vb 36 37 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 38 "value in MethodA is " & value & " after entering MethodA" 39 value += 1 40 lblOutput.Text &= vbCrLf & "local variable " & _ 41 "value in MethodA is " & value & " before exiting MethodA" 42 End Sub ' MethodA 43 44 ' uses instance variable value 45 Sub MethodB() 46 lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _ 47 " value is " & value & " after entering MethodB" 48 value *= 10 49 lblOutput.Text &= vbCrLf & "instance variable " & _ 50 "value is " & value & " before exiting MethodB" 51 End Sub ' MethodB 52 53 End Class ' FrmScoping When MethodB procedure refers to variable value , the instance variable value (line 12) is used.
37.
38. RandomInteger.vb 1 ' Fig. 6.14: RandomInteger.vb 2 ' Generating random integers. 3 4 Imports System.Windows.Forms 5 6 Module modRandomInteger 7 8 Sub Main() 9 Dim randomObject As Random = New Random() 10 Dim randomNumber As Integer 11 Dim output As String = "" 12 Dim i As Integer 13 14 For i = 1 To 20 15 randomNumber = randomObject.Next( 1 , 7 ) 16 output &= randomNumber & " " 17 18 If i Mod 5 = 0 Then ' is i a multiple of 5? 19 output &= vbCrLf 20 End If 21 22 Next 23 24 MessageBox.Show(output, "20 Random Numbers from 1 to 6" , _ 25 MessageBoxButtons. OK , MessageBoxIcon. Information ) 26 End Sub ' Main 27 28 End Module ' modRandomInteger Note that we must use 7 as the second argument to produce integers in the range from 1-6 Go to the next line every time five numbers are generated
39. RollDice.vb 1 ' Fig. 6.15: RollDice.vb 2 ' Rolling four dice. 3 4 Imports System.IO 5 6 Public Class FrmRollDice 7 Inherits System.Windows.Forms.Form 8 9 ' button for rolling dice 10 Friend WithEvents cmdRoll As System.Windows.Forms.Button 11 12 ' labels to display die images 13 Friend WithEvents lblDie1 As System.Windows.Forms.Label 14 Friend WithEvents lblDie2 As System.Windows.Forms.Label 15 Friend WithEvents lblDie3 As System.Windows.Forms.Label 16 Friend WithEvents lblDie4 As System.Windows.Forms.Label 17 18 ' Visual Studio .NET generated code 19 20 ' declare Random object reference 21 Dim randomNumber As Random = New Random() 22 23 ' display results of four rolls 24 Private Sub cmdRoll_Click( ByVal sender As System.Object, _ 25 ByVal e As System.EventArgs) Handles cmdRoll.Click 26 27 ' method randomly assigns a face to each die 28 DisplayDie(lblDie1) 29 DisplayDie(lblDie2) 30 DisplayDie(lblDie3) 31 DisplayDie(lblDie4) 32 End Sub ' cmdRoll_Click 33 Event-handling method cmdRoll_Click , executes whenever the user clicks cmdRoll RandomNumber is an instance variable of FrmRollDice . This allows the same Random object to be used each time DisplayDie executes
40. RollDice.vb 34 ' get a random die image 35 Sub DisplayDie( ByVal dieLabel As Label) 36 37 ' generate random integer in range 1 to 6 38 Dim face As Integer = randomNumber.Next( 1 , 7 ) 39 40 ' load corresponding image 41 dieLabel.Image = Image.FromFile( _ 42 Directory.GetCurrentDirectory & "magesie" & _ 43 face & ".png" ) 44 End Sub ' DisplayDie 45 46 End Class ' FrmRollDice Image property displays an image on the label Class Image is contained in the System.Drawing namespace, which is imported by default in all Windows Applications Method Directory.GetCurrentDirectory returns the location of the folder in which the current project is located, including bin
41. RollTwelveDice.vb 1 ' Fig. 6.16: RollTwelveDice.vb 2 ' Rolling 12 dice with frequency chart. 3 4 Imports System.IO 5 6 Public Class FrmRollTwelveDice 7 Inherits System.Windows.Forms.Form 8 9 ' labels to display die images 10 Friend WithEvents lblDie1 As System.Windows.Forms.Label 11 Friend WithEvents lblDie2 As System.Windows.Forms.Label 12 Friend WithEvents lblDie3 As System.Windows.Forms.Label 13 Friend WithEvents lblDie4 As System.Windows.Forms.Label 14 Friend WithEvents lblDie5 As System.Windows.Forms.Label 15 Friend WithEvents lblDie6 As System.Windows.Forms.Label 16 Friend WithEvents lblDie7 As System.Windows.Forms.Label 17 Friend WithEvents lblDie8 As System.Windows.Forms.Label 18 Friend WithEvents lblDie9 As System.Windows.Forms.Label 19 Friend WithEvents lblDie10 As System.Windows.Forms.Label 20 Friend WithEvents lblDie11 As System.Windows.Forms.Label 21 Friend WithEvents lblDie12 As System.Windows.Forms.Label 22 23 ' displays roll frequencies 24 Friend WithEvents displayTextBox As _ 25 System.Windows.Forms.TextBox 26 27 ' Visual Studio .NET generated code 28 29 ' declarations 30 Dim randomObject As Random = New Random() 31 Dim ones, twos, threes, fours, fives, sixes As Integer 32 We declare counters for each of the possible rolls The TextBox is used to display the cumulative frequencies of each face
42. RollTwelveDice.vb 35 Private Sub cmdRoll_Click _ 34 ( ByVal sender As System.Object, _ 35 ByVal e As System.EventArgs) Handles cmdRoll.Click 36 37 ' assign random faces to 12 dice using DisplayDie 38 DisplayDie(lblDie1) 39 DisplayDie(lblDie2) 40 DisplayDie(lblDie3) 41 DisplayDie(lblDie4) 42 DisplayDie(lblDie5) 43 DisplayDie(lblDie6) 44 DisplayDie(lblDie7) 45 DisplayDie(lblDie8) 46 DisplayDie(lblDie9) 47 DisplayDie(lblDie10) 48 DisplayDie(lblDie11) 49 DisplayDie(lblDie12) 50 51 Dim total As Integer = ones + twos + threes + fours + _ 52 fives + sixes 53 54 Dim output As String 55 56 ' display frequencies of faces 57 output = "Face" & vbTab & vbTab & _ 58 "Frequency" & vbTab & "Percent" 59 60 output &= vbCrLf & "1" & vbTab & vbTab & ones & _ 61 vbTab & vbTab & String .Format( "{0:P}" , ones / total) 62 63 output &= vbCrLf & "2" & vbTab & vbTab & twos & vbTab & _ 64 vbTab & String .Format( "{0:P}" , twos / total) 65 66 output &= vbCrLf & "3" & vbTab & vbTab & threes & vbTab & _ 67 vbTab & String .Format( "{0:P}" , threes / total) The “P” format code is used to display the frequency of each roll as percentages
43. RollTwelveDice.vb 68 69 output &= vbCrLf & "4" & vbTab & vbTab & fours & vbTab & _ 70 vbTab & String .Format( "{0:P}" , fours / total) 71 72 output &= vbCrLf & "5" & vbTab & vbTab & fives & vbTab & _ 73 vbTab & String .Format( "{0:P}" , fives / total) 74 75 output &= vbCrLf & "6" & vbTab & vbTab & sixes & vbTab & _ 76 vbTab & String .Format( "{0:P}" , sixes / total) & vbCrLf 77 78 displayTextBox.Text = output 79 End Sub ' cmdRoll_Click 80 81 ' display a single die image 82 Sub DisplayDie( ByVal dieLabel As Label) 83 84 Dim face As Integer = randomObject.Next( 1 , 7 ) 85 86 dieLabel.Image = _ 87 Image.FromFile(Directory.GetCurrentDirectory & _ 88 "magesie" & face & ".png" ) 89 90 ' maintain count of die faces 91 Select Case face 92 93 Case 1 94 ones += 1 95 96 Case 2 97 twos += 1 98 99 Case 3 100 threes += 1 101 Select Case is used to calculate the frequency
44. RollTwelveDice.vb 102 Case 4 103 fours += 1 104 105 Case 5 106 fives += 1 107 108 Case 6 109 sixes += 1 110 111 End Select 112 113 End Sub ' DisplayDie 114 115 End Class ' FrmRollTwelveDice
45.
46. CrapsGame.vb 1 ' Fig 6.17: CrapsGame.vb 2 ' Playing a craps game. 3 4 Imports System.IO 5 6 Public Class FrmCrapsGame 7 Inherits System.Windows.Forms.Form 8 9 Friend WithEvents cmdRoll As Button ' rolls dice 10 Friend WithEvents cmdPlay As Button ' starts new game 11 12 ' dice displayed after each roll 13 Friend WithEvents picDie1 As PictureBox 14 Friend WithEvents picDie2 As PictureBox 15 16 ' pointDiceGroup groups dice representing player's point 17 Friend WithEvents pointDiceGroup As GroupBox 18 Friend WithEvents picPointDie1 As PictureBox 19 Friend WithEvents picPointDie2 As PictureBox 20 21 Friend WithEvents lblStatus As Label 22 23 ' Visual Studio .NET generated code 24 25 ' die-roll constants 26 Enum DiceNames 27 SNAKE_EYES = 2 28 TREY = 3 29 CRAPS = 7 30 YO_LEVEN = 11 31 BOX_CARS = 12 32 End Enum 33 A GroupBox is a container used to group related components Enum erations are used to define groups of related constants
47. CrapsGame.vb 34 ' file-name and directory constants 35 Const FILE_PREFIX As String = "/images/die" 36 Const FILE_SUFFIX As String = ".png" 37 38 Dim myPoint As Integer 39 Dim myDie1 As Integer 40 Dim myDie2 As Integer 41 Dim randomObject As Random = New Random() 42 43 ' begins new game and determines point 44 Private Sub cmdPlay_Click( ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdPlay.Click 46 47 ' initialize variables for new game 48 myPoint = 0 49 pointDiceGroup.Text = "Point" 50 lblStatus.Text = "" 51 52 ' remove point-die images 53 picPointDie1.Image = Nothing 54 picPointDie2.Image = Nothing 55 56 Dim sum As Integer = RollDice() 57 58 ' check die roll 59 Select Case sum 60 61 Case DiceNames. CRAPS , DiceNames. YO_LEVEN 62 63 ' disable roll button 64 cmdRoll.Enabled = False 65 lblStatus.Text = "You Win!!!" 66 Keyword Const creates a single constant identifier in which values cannot be modified after they are declared Keyword Nothing can be used with reference-type variables to specify that no object is associated with the variable Setting the Image property to Nothing causes the PictureBoxes to appear blank The Select structure analyzes the roll returned by RollDice to determine how play should continue
48. CrapsGame.vb 67 Case DiceNames. SNAKE_EYES , _ 68 DiceNames. TREY , DiceNames. BOX_CARS 69 70 cmdRoll.Enabled = False 71 lblStatus.Text = "Sorry. You Lose." 72 73 Case Else 74 myPoint = sum 75 pointDiceGroup.Text = "Point is " & sum 76 lblStatus.Text = "Roll Again!" 77 DisplayDie(picPointDie1, myDie1) 78 DisplayDie(picPointDie2, myDie2) 79 cmdPlay.Enabled = False 80 cmdRoll.Enabled = True 81 82 End Select 83 84 End Sub ' cmdPlay_Click 85 86 ' determines outcome of next roll 87 Private Sub cmdRoll_Click( ByVal sender As System.Object, _ 88 ByVal e As System.EventArgs) Handles cmdRoll.Click 89 90 Dim sum As Integer = RollDice() 91 92 ' check outcome of roll 93 If sum = myPoint Then 94 lblStatus.Text = "You Win!!!" 95 cmdRoll.Enabled = False 96 cmdPlay.Enabled = True 97 ElseIf sum = DiceNames. CRAPS Then 98 lblStatus.Text = "Sorry. You Lose." 99 cmdRoll.Enabled = False 100 cmdPlay.Enabled = True 101 End If Disabling a Button causes no action to be performed when the Button is clicked
49. CrapsGame.vb 102 103 End Sub ' cmdRoll_Click 104 105 ' display die image 106 Sub DisplayDie( ByVal picDie As PictureBox, _ 107 ByVal face As Integer ) 108 109 ' assign die image to picture box 110 picDie.Image = _ 111 Image.FromFile(Directory.GetCurrentDirectory & _ 112 FILE_PREFIX & face & FILE_SUFFIX ) 113 End Sub ' DisplayDie 114 115 ' generate random die rolls 116 Function RollDice() As Integer 117 Dim die1, die2 As Integer 118 119 ' determine random integer 120 die1 = randomObject.Next( 1 , 7 ) 121 die2 = randomObject.Next( 1 , 7 ) 122 123 ' display rolls 124 DisplayDie(picDie1, die1) 125 DisplayDie(picDie2, die2) 126 127 ' set values 128 myDie1 = die1 129 myDie2 = die2 130 131 Return die1 + die2 132 End Function ' RollDice 133 134 End Class ' FrmCrapsGame RollDice generates two random numbers and calls method DisplayDie , which loads an appropriate die image on the PictureBox passed to it.
52. 6.14 Recursion Fig. 6.18 Recursive evaluation of 5!. 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 Final value = 120 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 3! = 3 * 2 = 6 is returned 2! = 2 * 1 = 2 is returned 1 returned (a) Procession of recursive calls (b) Values returned from each recursive call
53. Factorial.vb 1 ' Fig. 6.19: Factorial.vb 2 ' Calculating factorials using recursion. 3 4 Public Class FrmFactorial 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblEnter As Label ' prompts for Integer 8 Friend WithEvents lblFactorial As Label ' indicates output 9 10 Friend WithEvents txtInput As TextBox ' reads an Integer 11 Friend WithEvents txtDisplay As TextBox ' displays output 12 13 Friend WithEvents cmdCalculate As Button ' generates output 14 15 ' Visual Studio .NET generated code 16 17 Private Sub cmdCalculate_Click( ByVal sender As System.Object, _ 18 ByVal e As System.EventArgs) Handles cmdCalculate.Click 19 20 Dim value As Integer = Convert.ToInt32(txtInput.Text) 21 Dim i As Integer 22 Dim output As String 23 24 txtDisplay.Text = "" 25 26 For i = 0 To value 27 txtDisplay.Text &= i & "! = " & Factorial(i) & vbCrLf 28 Next 29 30 End Sub ' cmdCalculate_Click Conversion from String to Integer
54. Factorial.vb 31 32 ' recursively generates factorial of number 33 Function Factorial( ByVal number As Long ) As Long 34 35 If number <= 1 Then ' base case 36 Return 1 37 Else 38 Return number * Factorial(number - 1 ) 39 End If 40 41 End Function ' Factorial 42 43 End Class ' FrmFactorial If number is greater than 1 , a recursive call to Factorial is made with a slightly simpler problem Forgetting to return a value from a recursive procedure can result in logic errors
55.
56. Fibonacci.vb 1 ' Fig. 6.20: Fibonacci.vb 2 ' Demonstrating Fibonacci sequence recursively. 3 4 Public Class FrmFibonacci 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblPrompt As Label ' prompts for input 8 Friend WithEvents lblResult As Label ' displays result 9 10 Friend WithEvents cmdCalculate As Button ' calculates result 11 12 Friend WithEvents txtInputBox As TextBox ' reads an Integer 13 14 ' Visual Studio .NET generated code 15 16 ' displays Fibonacci number in txtInputBox 17 Private Sub cmdCalculate_Click( ByVal sender As System.Object, _ 18 ByVal e As System.EventArgs) Handles cmdCalculate.Click 19 20 ' read input 21 Dim number As Integer = Convert.ToInt32(txtInputBox.Text) 22 23 lblResult.Text = "Fibonacci Value is " & Fibonacci(number) 24 End Sub ' cmdCalculate_Click 25 26 ' calculate Fibonacci value recusively 27 Function Fibonacci( ByVal number As Integer ) As Long 28 29 ' check for base cases 30 If number = 1 OrElse number = 0 Then 31 Return number 32 Else 33 Return Fibonacci(number - 1 ) + Fibonacci(number - 2 ) 34 End If 35 This call to Fibonacci is not a recursive call If number is greater than 1 , the recursion step generates two recursive calls
57. Fibonacci.vb 36 End Function ' Fibonacci 37 38 End Class ' FrmFibonacci
58. 6.15 Example Using Recursion: Fibonacci Series Fig. 6.21 Recursive calls to method Fibonacci (abbreviated as F). Fibonacci( 3 ) Fibonacci( 2 ) Fibonacci( 1 ) Fibonacci( 0 ) Fibonacci( 1 ) return 1 return return 1 return 0 return
59.
60.
61. Overload.vb 1 ' Fig. 6.22: Overload.vb 2 ' Using overloaded methods. 3 4 Public Class FrmOverload 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents outputLabel As Label 8 9 ' Visual Studio .NET generated code 10 11 Private Sub FrmOverload_Load( ByVal sender As System.Object, _ 12 ByVal e As System.EventArgs) Handles MyBase .Load 13 14 outputLabel.Text = "The square of Integer 7 is " & _ 15 square( 7 ) & vbCrLf & "The square of Double " & _ 16 "7.5 is " & square( 7 . 5 ) 17 End Sub ' FrmOverload_Load 18 19 Function Square( ByVal value As Integer ) As Integer 20 Return Convert.ToInt32(value ^ 2 ) 21 End Function ' Square 22 23 Function Square( ByVal value As Double ) As Double 24 Return value ^ 2 25 End Function ' Square 26 27 End Class ' FrmOverload The compiler uses a logical name to differ between the two Square methods The compiler might use the logical name “ Square of Integer ” “ Square of Double ” for the Square method that specifies a Double parameter
62. Overload2.vb 1 ' Fig. 6.23: Overload2.vb 2 ' Using overloaded procedures with identical signatures and 3 ' different return types. 4 5 Public Class FrmOverload2 6 Inherits System.Windows.Forms.Form 7 8 Friend WithEvents outputLabel As Label 9 10 ' Visual Studio .NET generated code 11 12 Private Sub FrmOverload2_Load( ByVal sender As System.Object, _ 13 ByVal e As System.EventArgs) Handles MyBase .Load 14 15 outputLabel.Text = "The square of Integer 7 is " & _ 16 square( 7 ) & vbCrLf & "The square of Double " & _ 17 "7.5 is " & square( 7 . 5 ) 18 End Sub ' FrmOverload2_Load 19 20 Function Square( ByVal value As Double ) As Integer 21 Return Convert.ToInt32(value ^ 2 ) 22 End Function ' Square 23 24 Function Square( ByVal value As Double ) As Double 25 Return value ^ 2 26 End Function ' Square 27 28 End Class ' FrmOverload2 Procedure calls cannot be distinguished by return type
63. Overload2.vb Program Output The creating of overloaded procedures with identical parameter lists and different return types produces a syntax error
64.
65. Power.vb 1 ' Fig 6.24 Power.vb 2 ' Calculates the power of a value, defaults to square. 3 4 Public Class FrmPower 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents txtBase As TextBox ' reads base 8 Friend WithEvents txtPower As TextBox ' reads power 9 10 Friend WithEvents inputGroup As GroupBox 11 12 Friend WithEvents lblBase As Label ' prompts for base 13 Friend WithEvents lblPower As Label ' prompts for power 14 Friend WithEvents lblOutput As Label ' displays output 15 16 Friend WithEvents cmdCalculate As Button ' generates output 17 18 ' Visual Studio .NET generated code 19 20 ' reads input and displays result 21 Private Sub cmdCalculate_Click( ByVal sender As System.Object, _ 22 ByVal e As System.EventArgs) Handles cmdCalculate.Click 23 24 Dim value As Integer 25 26 ' call version of Power depending on power input 27 If Not txtPower.Text = "" Then 28 value = Power(Convert.ToInt32(txtBase.Text), _ 29 Convert.ToInt32(txtPower.Text)) 30 Else 31 value = Power(Convert.ToInt32(txtBase.Text)) 32 End If 33 34 lblOutput.Text = Convert.ToString(value) 35 End Sub ' cmdCalculate_Click Determines whether txtPower contains a value
66. Power.vb 36 37 ' use iteration to calculate power 38 Function Power( ByVal base As Integer , _ 39 Optional ByVal exponent As Integer = 2 ) As Integer 40 41 Dim total As Integer = 1 42 Dim i As Integer 43 44 For i = 1 To exponent 45 total *= base 46 Next 47 48 Return total 49 End Function ' Power 50 51 End Class ' FrmPower When omitted, the Optional argument defaults to the value 2
67.
68. DiceModule.vb 1 ' Fig. 6.25: DiceModule.vb 2 ' A collection of common dice procedures. 3 4 Imports System.IO 5 6 Module modDice 7 8 Dim randomObject As Random = New Random() 9 10 ' rolls single die 11 Function RollDie() As Integer 12 Return randomObject.Next( 1 , 7 ) 13 End Function ' RollDie 14 15 ' die summation procedure 16 Function RollAndSum( ByVal diceNumber As Integer ) _ 17 As Integer 18 19 Dim i As Integer 20 Dim sum As Integer = 0 21 22 For i = 1 To diceNumber 23 sum += RollDie() 24 Next 25 26 Return sum 27 End Function ' RollAndSum modDice groups several dice-related procedures into a module for reuse in other programs that use dice
69. DiceModule.vb 28 29 ' returns die image 30 Function GetDieImage( ByVal dieValue As Integer , _ 31 Optional ByVal baseImageName As String = "die" ) _ 32 As System.Drawing.Image 33 34 Return Image.FromFile( _ 35 Directory.GetCurrentDirectory & _ 36 "magesamp;quot; & baseImageName & dieValue & ".png" ) 37 End Function ' GetDieImage 38 39 End Module ' modDice Optional parameter baseImageName represents the prefix of the image name to be used
70. DiceModuleTest.vb 1 ' Fig. 6.26: DiceModuleTest.vb 2 ' Demonstrates modDiceModule procedures 3 4 Imports System.Drawing 5 6 Public Class FrmDiceModuleTest 7 Inherits System.Windows.Forms.Form 8 9 Friend WithEvents lblSum As Label ' displays 10-roll sum 10 11 Friend WithEvents diceGroup As GroupBox 12 13 ' dice images 14 Friend WithEvents picDie1 As PictureBox 15 Friend WithEvents picDie2 As PictureBox 16 17 Friend WithEvents cmdRollDie1 As Button ' rolls blue die 18 Friend WithEvents cmdRollTen As Button ' simulates 10 rolls 19 Friend WithEvents cmdRollDie2 As Button ' rolls red die 20 21 ' Visual Studio .NET generated code 22 23 Private Sub cmdRollDie1_Click( ByVal sender As System.Object, _ 24 ByVal e As System.EventArgs) Handles cmdRollDie1.Click 25 26 picDie1.Image = modDice.GetDieImage(modDice.RollDie()) 27 End Sub ' cmdRollDie1_Click 28 29 Private Sub cmdRollDie2_Click( ByVal sender As System.Object, _ 30 ByVal e As System.EventArgs) Handles cmdRollDie2.Click 31 32 picDie2.Image = modDice.GetDieImage(modDice.RollDie(), _ 33 "redDie" ) 34 End Sub ' cmdRollDie2_Click 35 cmdRollDie2_Click uses the Optional argument to prefix the image name and select a different image We call procedures contained in modDice by following the module name with the dot ( . ) operator and the procedure name
71. DiceModuleTest.vb 36 Private Sub cmdRollTen_Click( ByVal sender As System.Object, _ 37 ByVal e As System.EventArgs) Handles cmdRollTen.Click 38 39 lblSum.Text = Convert.ToString(modDice.RollAndSum( 10 )) 40 End Sub ' cmdRollTen_Click 41 42 End Class ' FrmDiceModuleTest This procedure sets the Text property of lblSum to the result of 10 rolls