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

Similar documents
Programming Language 2 (PL2)

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

Outline. Data and Operations. Data Types. Integral Types

Object Oriented Programming with Visual Basic.Net

Introduction to Data Entry and Data Types

Microsoft Visual Basic 2015: Reloaded

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Microsoft Visual Basic 2005: Reloaded

Data Types. Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions

Data and Operations. Outline

BITG 1233: Introduction to C++

BASIC ELEMENTS OF A COMPUTER PROGRAM

Using Custom Number Formats

Visual C# Instructor s Manual Table of Contents

Language Fundamentals

C# MOCK TEST C# MOCK TEST I

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

Full file at

Objectives. Describe ways to create constants const readonly enum

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Tokens, Expressions and Control Structures

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

Chapter-8 DATA TYPES. Introduction. Variable:

Bit (0, 1) Byte (8 bits: 0-255) Numeral systems. Binary (bin) 0,1 Decimal (dec) 0, 1, 2, 3, Hexadecimal (hex) 0, 1, 2, 3, 1/13/2011

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

Declaration and Memory

UNIT- 3 Introduction to C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

.Net Technologies. Components of.net Framework

NCSS Statistical Software. The Data Window

Program Fundamentals

Java Notes. 10th ICSE. Saravanan Ganesh

IT 374 C# and Applications/ IT695 C# Data Structures

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

The C++ Language. Arizona State University 1

Values and Variables 1 / 30

Creating a C++ Program

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Getting started with Java

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Programming in C++ 6. Floating point data types

Introduction To C#.NET

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

CMPT 125: Lecture 3 Data and Expressions

Chapter 2: Using Data

Java Basic Datatypees

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

INTRODUCTION 1 AND REVIEW

CS313D: ADVANCED PROGRAMMING LANGUAGE

Question And Answer.

Chapter 1 Getting Started

Types and Expressions. Chapter 3

10/9/2012. Computers are machines that process data. assignment in C# Primitive Data Types. Creating and Running Your First C# Program

Reserved Words and Identifiers

LECTURE 02 INTRODUCTION TO C++

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Data Types and Expressions

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

1. Introduction to Microsoft Excel

COMP6700/2140 Data and Types

NOTES: Variables & Constants (module 10)

Full file at

Database Programming with SQL 5-1 Conversion Functions. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Types, Variables, and Constants

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Murach s Visual Basic 2012, C4 2013, Mike Murach & Associates, Inc. Slide 1. The built-in value types (continued)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Chapter 2: Basic Elements of C++

CEN 414 Java Programming

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2 Elementary Programming

Java Classes: Math, Integer A C S L E C T U R E 8

CSI33 Data Structures

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Fundamental of Programming (C)

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Computer Components. Software{ User Programs. Operating System. Hardware

Preview from Notesale.co.uk Page 6 of 52

CS149: Elements of Computer Science. Fundamental C++ objects

Number Representation & Conversion

VARIABLES AND CONSTANTS

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Types, Operators and Expressions

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

Fundamental of C programming. - Ompal Singh

1.1 Introduction to C Language. Department of CSE

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Basics of Java Programming

Transcription:

Agenda & Reading COMPSCI 80 S Applications Programming Programming Fundamentals Data s Agenda: Data s Value s Reference s Constants Literals Enumerations Conversions Implicitly Explicitly Boxing and unboxing ting Recommended Reading: Data s in Visual Basic http://msdn.microsoft.com/en-us/library/ffsdktda(vs.80).aspx Advanced Programming Using Visual Basic.NET Appendix B: Visual Basic Review of Introductory of VB.NET Concepts Microsoft Visual Basic 005 Step by Step Chapter 5: Visual Basic Variables and Formulas Hands-On Lab: Lab04 COMPSCI 80 04 VB.NET Programming VB.NET Has achieved popularity and widespread acceptance Is a powerful, full-featured, object-oriented development language Is easy to learn and use Note: Code is not case sensitive VB.NET compiler does not require indentation of code, but good programming practice encourages indentation Comment lines: Begin with a single quote (') Add explanations to code Are ignored by compiler COMPSCI 80 04 3 Data s Visual Basic.NET supplies a set of pre-defined data types that you can use for many of your programming elements s are divided into two categories: Value s store data directly in the variable Numeric Data s Integral and nonintegral numeric types Boolean, Char and Date Structure Enumerations Reference s store a memory address (address of the actual object in memory) in the variable String Arrays Class s COMPSCI 80 04 4

Value s : Numeric Integral s Data types for numeric data without decimals Byte Short Integer Long Size (bytes) 4 8 NonIntegral s Range 0 through 55-3768 through 3767 -,47,483,648 through,47,483,647-9,3,37,036,854,775,808 through 9,3,37,036,854,775,807 Data types for numeric data with decimals Float and double implement the specification of the IEEE 754 format types Decimal: smaller range, but has more precision, is typically useful in financial calculations Single Double Decimal Size 3-bit floating point 64-bit floating point 8-bit fixed point COMPSCI 80 04 5 Value s (con t) char type char Size Helpful methods: Char.IsDigit() Stores a unicode character Indicates whether a Unicode character is categorized as a decimal digit. Char.IsPunctuation() Indicates whether the specified Unicode character is categorized as a punctuation mark. Char.IsLetter() Indicates whether a Unicode character is categorized as an alphabetic letter. Console.WriteLine(Char.IsDigit(CharVar)) COMPSCI 80 04 6 Value s (con t) Boolean Discusses true and false values. When numeric data types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to numeric types, False becomes 0 and True becomes Cbool -> - Convert.ToInt3 -> Date Dim mybirthday As Date mybirthday = #3//006 07:00 AM# Discusses date and time values. Date values must be enclosed within number signs (#) and be in the format M/d/yyyy, for example #5/3/993#. If you do not include a time in a date/time literal, VB sets the time part of the value to the start of the day, that is, midnight. Boolean Date Size (bytes) 8 Range True or False January, 000 through December 3, 9999 COMPSCI 80 04 7 Value s (con t) Structure A structure is a generalization of the user-defined type (UDT) supported by previous versions of Visual Basic. In addition to fields, structures can expose properties, methods, and events You can combine data items of different types to create a structure Structures are useful when you want a single variable to hold several related pieces of information. Examples: Public Structure Int3 Public Const MaxValue As Integer Public Const MinValue As Integer Public Function ToString As String End Function End Structure Dim intmax As Integer = Int3.MaxValue Console.WriteLine(intMax) COMPSCI 80 04 8

Reference s String The String data type is a sequence of zero or more two-byte (6- bit) Unicode characters. The default value of String is Nothing (a null reference). Note that this is not the same as the empty string (value ""). Object Object variables are stored as 3-bit (4-byte) addresses that refer to objects. Array An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called the elements of the array. They are contiguous from index 0 through the highest index value COMPSCI 80 04 9 What is an Object Each object in Visual Basic.NET is defined by a class. Classes describe the fields, properties, methods, and events of an object. Objects are instances of classes; you can create as many objects you need once you have created a class. Examples: Cookie cutters and cookies. The cookie cutter is the class. It defines the characteristics of each cookie for instance, size and shape. The class is used to create objects. The objects are the cookies. Controls The controls on the Toolbox in Visual Basic.NET represent classes. When you drag and drop a control from the toolbox onto a form, you are actually creating an object an instance of a class. COMPSCI 80 04 0 Working with Objects Instantiating an Object Instantiation is the process by which an instance of a class is created and assigned to an object variable. Fields and Properties Dim p As New MyPoint() Properties and fields represent information stored in an object. x and y coordinates of a Point object Methods Methods are procedures defined within a class. ToString(): Converts this Point to a human-readable string. Member Access Accessing the members of an object by specifying, in order, the name of the object, a period, and the name of the member you want to use. COMPSCI 80 04 Value s Vs Reference s Value s Value types are stored directly on the stack. Their storage can only be accessed directly. A variable of a value type always contains a value of that type. For a variable of a value type, the default value is the result of initializing each variable member of the type to its default value. Reference s Reference s are stored on the run-time heap; they may only be accessed through a reference to that storage. A variable of reference type contains a reference to a value of that type. For a variable of a reference type, the default value is a null reference. y 3 COMPSCI 80 04 0 x 4

Variables A variable is a storage location in the computer s memory, used for holding information while the program is running The information that is stored in a variable may change, hence the name variable A variable declaration is a statement that causes Visual Basic.NET to create a variable in memory To declare a VB.NET variable: Syntax: Dim is a keyword VariableName is the name to be used As is a keyword Data is the type of the variable Variable Naming Conventions Dim VariableName As Data Dim i As Integer Each variable name should describe its use, e.g., itemsordered When multiple words are used in a name, capitalize the initials, except for the first one (again, itemsordered) Certain names should have a specific prefix, e.g., txt for Text Boxes, btn for Buttons COMPSCI 80 04 3 Assigning Data to Variables Assignment operator (=) assigns the value on the right to the variable named on the left side i = To declare and initialize a variable can be written in one statement Dim i As Integer = Several variables of the same data type can be declared in one statement Dim i, j, k As Integer If no value is assigned when declared Numeric variables have an initial value of 0 Boolean variables have an initial value of False Date variables have an initial value of //000 String and object variables have an initial value of nothing COMPSCI 80 04 4 Constants A constant also has a name and data type. But the values stored in constants cannot change. Constant must be initialized in the statement that declares them By convention, constant names are capitalized Examples: Const WIDTH As Integer = 00 Const PI = 3.45965358979 Const VERSION = "07.0.A Const PI = PI * To declare multiple constants on a single line: Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44 COMPSCI 80 04 5 Literals "He said, ""I like it. """ String Literals String literals may contain letters, digits, and special characters and they are enclosed in quotation marks If you want to include quotation marks inside a string literal, use two quotation marks together You can force a literal to a particular data type by appending a type-declaration character. Data Short Integer Long Decimal Single Double Char Character S I L D F R C Example AGE = 35S HOURS = 40I POPULATION=0500L RATE = 0.3D RATE = 0.3F SALES=356R a C COMPSCI 80 04 6

Enumerations Enumerations provide a convenient way to work with sets of related constants and to associate constant values with names. Visual Basic provides a number of useful enumerations. Example: Date Enumeration LongDate ShortDate LongTime ShortTime Use DateTime() Function to returns a string expression representing a date/time value. Dim TestDate As DateTime = #3//999# Dim strdate As String strdate = DateTime(TestDate, Date.LongDate) Console.WriteLine(strDate) User-defined enumeration: Friday, March, 999 Enum MyDays Sat Sun Console.WriteLine(Days.Sat) COMPSCI 80 End Enum 04 7 Conversions Converting data from one type to another is called type conversion Conversions are either widening or narrowing, depending on the data capacities of the types involved: Widening Conversion A conversion changes a value to a data type that can accommodate any possible value of the original data. Examples: Byte -> Short/Integer/Long/Decimal/Single/Double Single -> Double Narrowing conversion A conversion changes a value to a data type that might not be able to hold some of the possible values Narrowing conversions do not always succeed at run time, and can fail or incur data loss Double -> Single COMPSCI 80 04 8 Conversion Conversions are either implicit or explicit, depending on the syntax in the source code Implicit type conversion An implicit conversion does not require any special syntax in the source code. 4.0 Integer will implicitly convert to single Explicit type conversion An explicit conversion uses type conversion keywords, or Dim k As Integer Dim q As Single k = 4 q = k Dim b As Single =.4 Dim i As Integer i = CInt(b) Console.WriteLine(i) functions of the System.Convert class, or functions on an individual type structure or class. COMPSCI 80 04 9 Conversion keywords Conversion Functions coerce an expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code inline, so execution is slightly faster than with a function call. Keyword CBool(expression) CChar(expression) CInt(expression) C(expression, DestinationData) Range for expression argument Any valid Char or String or numeric expression. Any valid Char or String expression; only first character of a String is converted; value can be 0 through 65535 (unsigned). -,47,483,648 through,47,483,647; fractional parts are rounded. coerces expression to DestinationData, where DestinationData can be any data type, structure, or class to which there exists a valid conversion. COMPSCI 80 04 0

The Convert Class & Parse Method The convert class The Convert class contains methods to convert a base data type to another base data type. ToBoolean ToInt3(Single) The parse method Every numeric data type in Visual Basic.NET has a Parse method that can be used to convert a string to that numeric data type. This is handy for converting Text Property into a numeric variable without using the VAL function. Syntax: Convert.Toxxx(value) Dim purchase As Double = 500 Dim tax As Decimal = Convert.ToDecimal(purchase) *.03D Dim inumber As Integer = Convert.ToInt3(dNumber) Converts the value to an equivalent Boolean value. Converts the value of the specified single-precision floating point number to an equivalent 3-bit signed integer. numericdata.parse(string) Note: If value is halfway between two whole numbers, the even number is returned Dim sales As Decimal sales = Decimal.Parse(uiSalesTextBox.Text) COMPSCI 80 04 Boxing and unboxing Boxing and unboxing enable value types to be treated as objects With boxing and unboxing one can link between valuetypes and reference-types by allowing any value of a value type to be converted to and from type object. Boxing Put a value type into an instance of the Object reference type Unboxing i = 3 Dim o As Object = i 'boxing Extract the value type from the object Dim j As Integer = o 'unboxing Note: boxing and unboxing are computationally expensive processes COMPSCI 80 04 ting The.NET Framework defines standard and custom format specifiers for formatting numbers, dates and times, and enumerations specifiers are used by various methods that format output strings, such as Console.WriteLine and the ToString method of any type. Examples: Using Console.Write/WriteLine Using ToString Character C F N X Description Currency Fixed-point Number Hexadecimal Console.WriteLine("{0:F}",.5) Console.WriteLine("{0:F4}",.5) Dim d As Double =.5 Console.WriteLine(d.ToString("c")) Console.WriteLine(d.ToString("f")) Examples 500000 Output $.5.50,500,000.00 9 COMPSCI 80 04 3.5.5 5 $.50.50.50.5000 DateTime ting Standard DateTime Strings Consists of a single format specifier character from the following table Dim dt As DateTime = DateTime.Now Console.WriteLine(dt.ToString("d")) Console.WriteLine(dt.ToString("D")) Strings dd ddd dddd DateTime for a specific culture Custom DateTime Strings Meaning current day of the month; -3 abbreviated name of the day full name of the day Strings MM MMM MMMM Meaning the month, - abbreviated name of the month full name of the month German in Germany 09.0.007 ci = New System.Globalization.CultureInfo("de-DE") Console.WriteLine(dt.ToString("d", ci)) Console.WriteLine(dt.ToString("dddd, dd - MMMM")) Strings COMPSCI 80 04 4 yy yyyy /9/007 Tuesday, 9 January 007 Meaning the year, as a maximum two-digit number (The first two digits of the year are omitted) the year Specifier d/d t/t g/g f/f M,m Name Short/Long date Short/long time Short/long General date/time Short/long Full date/time Month day Y,y Year month Tuesday, 09 - January

Option Strict Placed the Option Strict On statement at the very top of the code window this will prevent VB.NET from performing implicit data type conversion from a wider data type to a narrow one, or between String and numeric data types Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity Dim x As Integer Dim y As Byte Option Strict Off y = 30 x = y Console.WriteLine(x) 'narrowing conversion x = 300 y = x Console.WriteLine(y) Option Strict On y = 30 x = y Console.WriteLine(x) x = 300 y = x Console.WriteLine(y) Generate Compile-time Compiled OK error COMPSCI 80 Generate run-time error 04 5 Option Explicit VB.NET provides a way to prevent you from using undeclared variables in your code Enter the statement Option Explicit On at the very top of the code window This may already be turned on. Choose Tools->Options, Projects, VBDefaults COMPSCI 80 04 6