Section 7 The BASIC Language II

Similar documents
Revision for Final Examination (Second Semester) Grade 9

Learning VB.Net. Tutorial 19 Classes and Inheritance

Mr.Khaled Anwar ( )

11. Persistence. The use of files, streams and serialization for storing object model data

In this tutorial we will create a simple calculator to Add/Subtract/Multiply and Divide two numbers and show a simple message box result.

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET

Lecture 10 OOP and VB.Net

Text Input and Conditionals

Learning VB.Net. Tutorial 10 Collections

Else. End If End Sub End Class. PDF created with pdffactory trial version

About this exam review

DroidBasic Syntax Contents

Unit 3: Multiplication and Division Reference Guide pages x 7 = 392 factors: 56, 7 product 392

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

6.1 Evaluate Roots and Rational Exponents

VB FUNCTIONS AND OPERATORS

Standard ADTs. Lecture 19 CS2110 Summer 2009

1. Introduction to Microsoft Excel

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Déclaration du module

Function: function procedures and sub procedures share the same characteristics, with

Arrays, Strings and Collections

IMS1906: Business Software Fundamentals Tutorial exercises Week 5: Variables and Constants

VISUAL BASIC 2005 EXPRESS: NOW PLAYING

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

To enter the number in decimals Label 1 To show total. Text:...

CS313D: ADVANCED PROGRAMMING LANGUAGE

DEVELOPING OBJECT ORIENTED APPLICATIONS

OVERLOADING METHODS AND CONSTRUCTORS: The Ball Class

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces.

DRAWING AND MOVING IMAGES

Syntax. Table of Contents

Access Intermediate

EnableBasic. The Enable Basic language. Modified by Admin on Sep 13, Parent page: Scripting Languages

EXAMGOOD QUESTION & ANSWER. Accurate study guides High passing rate! Exam Good provides update free of charge in one year!

Lab 6: Making a program persistent

Rev Name Date. . Round-off error is the answer to the question How wrong is the rounded answer?

cs1114 REVIEW of details test closed laptop period

Herefordshire College of Technology Centre Edexcel BTEC Level 3 Extended Diploma in Information Technology (Assignment 1 of 3)

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Problem One: Loops and ASCII Graphics

Using Custom Number Formats

1. Create your First VB.Net Program Hello World

You must bring your ID to the exam.

CALIFORNIA STATE UNIVERSITY, SACRAMENTO College of Business Administration. MIS 15 Introduction to Business Programming. Programming Assignment 3 (P3)

CSE 373: Data Structures and Algorithms

Computer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving

ONLINE BOOKING GUIDE

IRESS Depth - Web Services Version 4 Walkthrough Visual Basic 2008 sample to retrieve IRESS Depth information

IOS Plus Trade - Web Services Version 4 Walkthrough

Module 4: Data Types and Variables

Week 6. Data structures

Chapter 2.4: Common facilities of procedural languages

Data Structures and Algorithms in Java. Second Year Software Engineering

CS313D: ADVANCED PROGRAMMING LANGUAGE

Excel VBA Variables, Data Types & Constant

CSE373 Winter 2014, Final Examination March 18, 2014 Please do not turn the page until the bell rings.

C4.3, 4 Lab: Conditionals - Select Statement and Additional Input Controls Solutions

Python Lists, Tuples, Dictionaries, and Loops

Review. October 20, 2006

CS112 Lecture: Working with Numbers

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

7. Inheritance & Polymorphism. Not reinventing the wheel

FUNDAMENTAL ARITHMETIC


Repetition Structures

Getting Information from a Table

Fun facts about recursion

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

General Instructions. You can use QtSpim simulator to work on these assignments.

COMP 103 Introduction to Data Structures and Algorithms

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

EXAM Computer Science 1 Part 1

Module 6: Fundamentals of Object- Oriented Programming

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Variable A variable is a value that can change during the execution of a program.

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

CSE373 Fall 2013, Second Midterm Examination November 15, 2013

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Burrows & Langford Chapter 10 page 1 Learning Programming Using VISUAL BASIC.NET

CS 101 Spring 2006 Final Exam Name: ID:

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Language Fundamentals

Exponential Numbers ID1050 Quantitative & Qualitative Reasoning

Data Structures - CSCI 102. CS102 Hash Tables. Prof. Tejada. Copyright Sheila Tejada

Running the Altair SIMH from.net programs

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Expressing Decimal Numbers in Word Form

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

An overview about DroidBasic For Android

Learning VB.Net. Tutorial 16 Modules

How to Validate DataGridView Input

Data Structures and Algorithms 2018

PROGRAMMING ASSIGNMENT: MOVIE QUIZ

CS313D: ADVANCED PROGRAMMING LANGUAGE

MATFOR In Visual Basic

TREES 11/1/18. Prelim Updates. Data Structures. Example Data Structures. Tree Overview. Tree. Singly linked list: Today: trees!

Department of Computer Science Admission Test for PhD Program. Part I Time : 30 min Max Marks: 15

PLT Fall Shoo. Language Reference Manual

Transcription:

Dates Section 7 The BASIC Language II The Date class holds a date (between January 1 st, 0001 and December 31 st, 9999) combined with a time (between 0:00:00 and 23:59:59) Constructors of the Date class allow you to initialise it with day, month, year, etc. The CDate( ) function converts a String to a Date, but will generate an error if the String isn t appropriate use of the IsDate( ) function is recommended Dim s As String = "21/12/1908" Dim d As Date If IsDate(s) Then d = CDate(s) MsgBox(d.ToLongDateString()) End If To add and subtract dates, use: DateAdd(interval, number, date) Dim d As New Date(2008, 2, 25) Dim d2 As Date d2 = DateAdd(DateInterval.Day, 5, d) MsgBox("5 days after " & d.toshortdatestring() & " is " & d2.toshortdatestring()) d2 = DateAdd(DateInterval.Month, -6, d) MsgBox("6 months before " & d.toshortdatestring() & " is " & d2.toshortdatestring())

To calculate the difference (elapsed period) between two dates, use: DateDiff(interval, date1, date2) Dim i As Long i = DateDiff(DateInterval.Day, d, d2) To extract a specified component (year, month, minute, etc.) from a date, use: DatePart(interval, date) MsgBox("The current hour is: " & DatePart(DateInterval.Hour, Now())) The DateTimePicker control Makes it very simple for users to enter a Date, Time, or Date+Time The Value property gives you the actual date selected

Use the Format property to specify what you want to be displayed and selectable by the user Format Long : Format Short : Format Time : Built-in Data Structures Arrays o Fundamental mechanism in computing o One name, multiple values, arranged as an indexed list.net Collection Classes o ArrayLists o HashTables o Dictionaries

o Stacks and Queues Arrays: Lists of items are written, one at a time, to successive slots in an array Items can be retrieved by index The array can be reorganized e.g. sorted into alphabetical or numeric order, items removed, inserted etc. Limitations are as for any type of list: o Difficult to insert items without disturbing existing ones (unless empty space is built-in) o Removing an item leaves a hole o Locating an item usually requires an exhaustive search (start at first item and check each until desired item is found) Overcoming these limitations requires programming, or using an alternative data structure Other Data Structures / Collection Classes: ArrayList o Like an array, but no need to specify size o Add new items with the.add() method HashTable o A fast-access data structure. Items are searched/retrieved in a time that is almost independent of the number of them o Uses a Key object (usually a string) as a lookup value for the Item Queue o Like a real queue items join at the back and leave from the front SortedList

o Items added to a SortedList are inserted into the list in a pre-defined order (alphabetical, numerical, by date etc.). o Insertion is slower than adding an item to the end of an array, but retrieval is much faster (binary search) Stack o A pile of items added to and removed from the top only Collection o A general-purpose list of arbitrary items/objects, held in the order they were added in Dictionary o A Key-Value pair list, designed, like HashTable, for looking up items by their associated key. o Available only as a base class for customizing to a specific purpose Collections A collection object allows you to store members of any data type, including object data types and even other collection objects, and retrieve them using a unique key Similar to associative arrays in other modern languages (which refers to an array indexed by something more meaningful than a simple number) Methods of the Collection class: o Add (item [, key, before, after] ) If you don t specify before or after, the item is added at the end

If you don t specify a key, the item is indexed by integer (same as an array) o Count o Item(key) o Remove(key) Example: (BankCollection.sln) Public Class Form1 Dim accounts As New Collection ' collection of bank accounts Dim b As BankAccount ' currently logged-in instance Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.Height = 126 Private Sub btnlogin_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.click ' does account exist with this name? Try b = accounts.item(txtname.text) ' account exists: is password correct? If (b.testpassword(txtpassword.text)) Then ' password correct ' flow of control will pass to below the Try..End Try block Else ' password wrong MsgBox("Incorrect Password!", MsgBoxStyle.Critical) Return End If Catch ' no account with that name: create one? Dim prompt As String prompt = "There is no account with the name " & txtname.text & ", do you want to create one?" If MsgBox(prompt, MsgBoxStyle.Information Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

0) ' do create one b = New BankAccount(txtName.Text, txtpassword.text, accounts.add(b, txtname.text) Else ' don't create one Return End If End Try ' we only arrive here if an account is logged in Me.Height = 223 txtdetails.text = b.getdetails() Private Sub btndeposit_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btndeposit.click Dim amt As Integer Try amt = CInt(InputBox("Deposit How Much? ")) b.deposit(amt) txtdetails.text = b.getdetails() Catch End Try Private Sub btnwithdraw_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btnwithdraw.click Dim amt As Integer Try amt = CInt(InputBox("Withdraw How Much? ")) b.withdraw(amt) txtdetails.text = b.getdetails() Catch End Try End Class Public Class BankAccount Public AccountName As String Private Password As String Private Balance As Decimal Public Sub New(ByVal Name As String) AccountName = Name Public Sub New(ByVal Name As String, ByVal Pass As String, ByVal Initial As Decimal) AccountName = Name Password = Pass Balance = Initial Public Sub Deposit(ByVal amt As Integer) Balance += amt Public Sub Withdraw(ByVal amt As Integer) Balance -= amt

Public Function GetDetails() Return AccountName & ControlChars.CrLf & "Balance: " & Balance End Function Public Function testpassword(byval Pass As String) Return (Pass = Password) End Function End Class To iterate through objects held in a Collection Classes, use For Each : Dim s As String = "" Dim ba As BankAccount For Each ba In accounts s = s & ba.getdetails() & ControlChars.CrLf Next MsgBox(s) HashTable example: Note that Hash Tables do not easily support being iterated through The point of a HashTable is to provide fast look-up (random) access to the elements, not to provide access to the elements in sequence Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ht As New Hashtable Dim P1 As New Person(111, "Saravanan", 26) Dim P2 As New Person(222, "Selvakumar", 26) Dim P3 As New Person(333, "Venkatesh", 27) ht.add(p1.id, P1) ht.add(p2.id, P2) ht.add(p3.id, P3) Console.WriteLine("Number of items in the HashTable are : " & ht.count) Dim P As Person If ht.contains(111) Then Console.WriteLine("Record Found!") P = CType(ht.Item(111), Person) Console.WriteLine("The age of " & P.name & " is " & P.age) Else Console.WriteLine("Record Not Found!")

End If End Class Public Class Person Public id As Integer Public name As String Public age As Integer Public Sub New(ByVal i As Integer, ByVal s As String, ByVal a As Integer) id = i name = s age = a End Class Queue Example: Dim q As New Queue q.enqueue("one") q.enqueue("two") q.enqueue("three") q.enqueue("four") q.enqueue("five") Console.WriteLine("Number of items in the Queue are : " & q.count) While q.count > 0 Console.WriteLine(q.Dequeue()) End While Stack Example: Dim s As New Stack s.push("one") s.push("two") s.push("three") s.push("four") s.push("five") Console.WriteLine("Number of items in the Stack are : " & s.count) While s.count > 0 Console.WriteLine(s.Pop()) End While Advantages of Sorted Lists In a list of items in random order, it is necessary to do an exhaustive search when looking for an item that might be in the list Just because we have not met it yet does not mean it is not there

With a sorted list, it is only necessary to look until you reach the point where the item should have been inserted (in the sort order) For example, searching for a particular Smith in the phone book, you would know to give up once you got beyond the entries for Smith There are even bigger benefits to searching a sorted list, since it is possible to use a Binary Search algorithm At each step of the search, able to dismiss ½ of the remaining items To perform a binary search in.net, use a SortedList collection, or an Array to which the Sort() method has been applied, and use the BinarySearch method (see section 3 of this course) Formatting Numbers The FormatNumber() function returns a value formatted as a number. Its general format is: FormatNumber(value [, trailing digits] [, leading digit] [, parentheses] [, group digits])

trailing digits is an integer giving the number of digits following the decimal point; the default is rounding to 2 digits leading digit (Boolean) indicates whether a leading 0 is to appear before the decimal point for fractional values parentheses (Boolean) indicates whether negative numbers should be displayed inside parentheses group digits (Boolean) indicates whether numbers should be grouped between commas. Format Output FormatNumber(12345.6789) 12,345.68 FormatNumber(12345.6789,5) 12,345.67890 FormatNumber(12345.6789,,,,False) 12345.68 FormatNumber(-12345.6789) -12,345.68 FormatNumber(-12345.6789,,,True) (12,345.68) FormatNumber(.6789) 0.68 FormatNumber(.6789,,False).68 FormatNumber(-.6789,4) -0.6789 Formatting Dates and Times The FormatDateTime() function returns a string expression representing a date/time value: FormatDateTime(value [, DateFormat.format]) value is a date or time value format is one of the following values: GeneralDate, LongDate, ShortDate, LongTime, or ShortTime. FormatDateTime(Now) Format Output 3/6/2008 5:25:55 PM

FormatDateTime(Today) 3/6/2008 FormatDateTime(TimeOfDay) 5:25:55 PM FormatDateTime(Now,DateFormat.LongDate) Thursday, March 06, 2008 FormatDateTime(Today,DateFormat.LongDate) Thursday, March 06, 2008 FormatDateTime(Now,DateFormat.ShortDate) 3/6/2008 FormatDateTime(Today,DateFormat.ShortDate) 3/6/2008 FormatDateTime(Now,DateFormat.LongTime) 5:25:55 PM FormatDateTime(TimeOfDay,DateFormat.LongTime) 5:25:55 PM FormatDateTime(Now,DateFormat.ShortTime) 17:25 FormatDateTime(TimeOfDay,DateFormat.ShortTime) 17:25 General Formatting The Format() function is a general-purpose function that returns a string value formatted according to a format string. The format strings duplicate numeric and date/time formats produced by the specialized formats described above. Format(value, "format string") The characters shown in the following table are used to compose the format string. Character 0 #., Description Digit placeholder. Displays a digit or a zero. If the value has a digit in the position, then it displays; otherwise, a zero is displayed. Digit placeholder. Displays a digit or a space. If the value has a digit in the position, then it displays; otherwise, a space is displayed. Decimal placeholder; determines how many digits are displayed to the left and right of the decimal separator. Thousand separator; separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Only a single "," is required in the format, between the first set of digit

% placeholders. Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears in the format string. - + $ ( ) Literal characters; displayed exactly as typed in the format string. Examples: Format Output Format(012345.6789,"0.00") 12345.68 Format(012345.6789,"0,0.000") 12,345.679 Format(012345.6789,"00000,0.000000") 012,345.678900 Format(012345.6789,"#.##") 12345.68 Format(012345.6789,"#,#.##") 12,345.68 Format(012345.6789,"$ #,#.##") $ 12,345.68 Format(-012345.6789,"#,#.####") -12,345.6789 Format(-012345.6789,"$#,#.##") -$12,345.68 Format(.6789,"#,#.##").68 Format(.6789,"0,0.000") 00.679 Format(-.6789," 0.0000") - 0.6789 Format(.6789,"0.00%") 67.89%