Presentation is loading. Please wait.

Presentation is loading. Please wait.

Based on Murach’s Chapter 4

Similar presentations


Presentation on theme: "Based on Murach’s Chapter 4"— Presentation transcript:

1 Based on Murach’s Chapter 4
How to work with numeric and string data Based on Murach’s Chapter 4

2 Objectives (Applied) Given an arithmetic expression and the values for the variables in the expression, evaluate the expression. Use numeric and string data as needed within your applications. That means you should be able to do any of the following: declare and initialize variables and constants code arithmetic expressions and assignment statements use the static methods of the Math class cast and convert data from one type to another use the correct scope for your variables declare and use enumerations work with nullable types and the null-coalescing operator

3 Objectives (Knowledge) cont.
Distinguish between a variable and a constant and give the naming conventions for each. Describe any of these data types: int, double, decimal, bool, and string. Describe any of these terms: literal value, null value, empty string, concatenate, append, escape sequence, string literal, verbatim string literal, and nullable data type. Describe the order of precedence for arithmetic expressions. Distinguish between implicit casting and explicit casting. Distinguish between a value type and a reference type. Describe the differences in the ways that casting, the ToString method of a data structure, the Parse and TryParse methods of a data structure, and the methods of the Convert class can be used to convert data from one form to another. Describe the differences between class scope and method scope.

4 The built-in value types

5 The built-in value types (cont.)

6 The built-in value types (cont.)

7 How to declare and initialize a variable in two statements
Syntax type variableName; variableName = value; Ex: int counter; counter = 1; Description A variable stores a value that can change as a program executes. Naming convention Start the names of variables with a lowercase letter, and capitalize the first letter of each word after the first word. This is known as camel notation.

8 How to declare and initialize a variable in one statement
Syntax type variableName = value; Ex: int counter = 1; long numberOfBytes = 20000; float interestRate = 8.125f; double price = 14.95; decimal total = m; double starCount = 3.65e+9; char letter = 'A'; bool valid = false; int x = 0, y = 0; //not the best way

9 How to declare and initialize a constant
Syntax const type ConstantName = value; Examples const int DaysInNovember = 30; const decimal SalesTax = .075m; Description A constant stores a value that can’t be changed. Naming convention Capitalize the first letter of each word of a constant name. This is known as Pascal notation.

10 Arithmetic operators

11 Arithmetic operators (cont.)

12 Arithmetic expressions that use integers
int x = 14; int y = 8; int result1 = x + y; // result1 = 22 int result2 = x - y; // result2 = 6 int result3 = x * y; // result3 = 112 int result4 = x / y; // result4 = 1 int result5 = x % y; // result5 = 6 int result6 = -y + x; // result6 = 8 int result7 = --y; // result7 = 7, y = 7 int result8 = ++x; // result8 = 15, x = 15

13 Arithmetic expressions that use decimals
decimal a = 8.5m; decimal b = 3.4m; decimal result11 = a + b; // result11 = 11.9 decimal result12 = a - b; // result12 = 5.1 decimal result13 = a / b; // result13 = 2.5 decimal result14 = a * b; // result14 = 28.90 decimal result15 = a % b; // result15 = 1.7 decimal result16 = -a; // result16 = -8.5 decimal result17 = --a; // result17 = 7.5, a = 7.5 decimal result18 = ++b; // result18 = 4.4, b = 4.4

14 Assignment operators

15 The syntax for a simple assignment statement
variableName = expression; Ex.: Typical assignment statements: counter = 7; newCounter = counter; discountAmount = subtotal * .2m; total = subtotal – discountAmount;

16 Statements that use the same variable on both sides of the equals sign
total = total + 100m; total = total – 100m; price = price * .8m; Statements that use the shortcut assignment operators total += 100m; total -= 100m; price *= .8m;

17 The order of precedence for arithmetic operations
Increment and decrement Positive and negative Multiplication, division, and modulus Addition and subtraction

18 A calculation that uses the default order of precedence
decimal discountPercent = .2m; // 20% discount decimal price = 100m; // $100 price price = price * 1 – discountPercent; // price = $99.8 A calculation that uses parentheses to specify the order of precedence price = price * (1 – discountPercent); // price = $80 The use of prefixed and postfixed increment and decrement operators int a = 5; int b = 5; int y = ++a; // a = 6, y = 6 int z = b++; // b = 6, z = 5

19 How implicit casting works
Casting from less precise to more precise data types byte à short à int à long à decimal                    int à double                                short à float à double char à int Examples double grade = 93; // convert int to double int letter = 'A'; // convert char to int double a = 95.0; int b = 86, c = 91; double average = (a+b+c)/3; // convert b and c to doubles // (average = )

20 How to code an explicit cast cont.
The syntax for coding an explicit cast (type) expression Ex: int grade = (int)93.75; // convert double to int // (grade = 93) char letter = (char)65; // convert int to char // (letter = 'A') ASCII double a = 95.0; int b = 86, c = 91; int average = ((int)a+b+c)/3; // convert a to int value // (average = 90) decimal result = (decimal)b/(decimal)c;// result has decimal // places

21 Five static methods of the Math class
The syntax of the Round method Math.Round(decimalNumber[, precision[, mode]]) The syntax of the Pow method Math.Pow(number, power) The syntax of the Sqrt method Math.Sqrt(number) The syntax of the Min and Max methods Math.{Min|Max}(number1, number2)

22 Statements that use static methods of the Math class
int shipWeight = Math.Round(shipWeightDouble);// round to a whole //number double orderTotal = Math.Round(orderTotal, 2);// round to 2 decimal //places double area = Math.Pow(radius, 2) * Math.PI; // area of circle double sqrtX = Math.Sqrt(x); double maxSales = Math.Max(lastYearSales, thisYearSales); int minQty = Math.Min(lastYearQty, thisYearQty);

23 Results from static methods of the Math class
Statement Result Math.Round(23.75, 1) Math.Round(23.85, 1) Math.Round(23.744, 2) Math.Round(23.745, 2) Math.Round(23.745, 2, MidpointRounding.AwayFromZero) 23.75 Math.Pow(5, 2) Math.Sqrt(20.25) Math.Max(23.75, 20.25) Math.Min(23.75, 20.25)

24 MidpointRounding Enumeration
AwayFromZero When a number is halfway between two others, it is rounded toward the nearest number that is away from zero. ToEven When a number is halfway between two others, it is rounded toward the nearest even number.

25 Details static Math class
To use one of the static methods of the Math class, code the class name, a dot, the method name, and one or more arguments in parentheses. The arguments provide the values that are used by the method.  The Round method rounds a decimal argument to the specified precision, which is the number of significant decimal digits. If the precision is omitted, the number is rounded to the nearest whole number.  By default, if you round a decimal value that ends in 5, the number is rounded to the nearest even decimal  value. This is referred to as banker’s rounding. You can also code the mode argument with a value of  MidpointRounding.AwayFromZero to round positive values up and negative values  down.  The Pow method raises the first argument to the power of the second argument. Both arguments must have the double data type.   The Sqrt method returns the square root of the specified argument, which can have any  numeric data type.  The Min and Max methods return the minimum and maximum of two numeric arguments.  The two arguments must have the same data type

26 How to declare and initialize a string
string message1 = "Invalid data entry."; string message2 = ""; string message3 = null; How to join strings string firstName = "Bob"; // firstName is "Bob" string lastName = "Smith"; // lastName is "Smith" string name = firstName + " " + lastName; // name is "Bob Smith" How to join a string and a number double price = 14.95; string priceString = "Price: $" + price; // priceString is "Price: $14.95" APPEND (+)

27 How to append one string to another string
string firstName = "Bob"; // firstName is "Bob" string lastName = "Smith"; // lastName is "Smith" string name = firstName + " "; // name is "Bob " name = name + lastName; // name is "Bob Smith" How to append one string to another with the += operator name += lastName; // name is "Bob Smith"

28 string ・ A string can consist of any characters in the character set including letters, numbers, and special characters like $, *, &, and #. ・ To specify the value of a string, you can enclose text in double quotes. This is known as a string literal. ・ To assign a null value to a string, you can use the null keyword. This means that the value of the string is unknown. ・ To assign an empty string to a string, you can code a set of double quotes with nothing between them. This usually indicates that the value of the string is known, but the string doesn’t contain any characters. ・ To join, or concatenate, a string with another string or a value data type, use a plus sign. If you concatenate a value data type to a string, C# will automatically convert the value to a string so it can be used as part of the string. ・ When you append one string to another, you add one string to the end of another. To do that, you can use assignment statements. The += operator is a shortcut for appending a string expression to a string variable.

29 Common escape sequences (special characters)

30 Examples that use escape sequences
Code Result string code = "JSPS"; decimal price = 49.50m; string result = "Code: " + code + "\n" + Code: JSPS "Price: $" + price + "\n"; Price: $49.50 string names = Joe Smith "Joe\tSmith\rKate\tLewis\r"; Kate Lewis string path = "c:\\c#.net\\files"; c:\c#.net\files string message = "Type \"x\" to exit"; Type "x" to exit

31 Examples that use verbatim string literals

32 Special Characters Within a string, you can use escape sequences to include certain types of special characters. To code a verbatim string literal, you can code sign, followed by an opening double quote, followed by the string, followed by a closing double quote. Within the string, you can enter backslashes, tabs, new line characters, and other special characters without using escape sequences. However, to enter a double quote within a verbatim string literal, you must enter two double quotes.

33 Common .NET structures that define value types

34 Common .NET classes that define reference types

35 .NET Built-in Data Types
・ Each built-in data type is supported by a structure or a class within the .NET Framework. When you use a C# keyword to refer to a data type, you’re actually using an alias for the associated structure or class. ・ A structure defines a value type, which stores its own data. ・ A class defines a reference type. A reference type doesn’t store the data itself. Instead, it stores a reference to the area of memory where the data is stored. ・ All of the structures and classes shown in so far are in the System namespace of the .NET Framework.

36 Common methods for data conversion

37 Parse vs TryPass Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded. TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false. In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

38 Some of the static methods of the Convert class
Method Description ToDecimal(value) Converts the value to the decimal data type. ToDouble(value) Converts the value to the double data type. ToInt32(value) Converts the value to the int data type. ToChar(value) Converts the value to the char data type. ToBool(value) Converts the value to the bool data type. ToString(value) Converts the value to a string object.

39 Statements that use ToString, Parse, and TryParse
decimal sales = m; string salesString = sales.ToString(); // decimal to string sales = Decimal.Parse(salesString); // string to decimal Decimal.TryParse(salesString, out sales); // string to decimal An implicit call of the ToString method double price = 49.50; string priceString = "Price: $" + price; // automatic ToString //call A TryParse method that handles invalid data string salesString = "$ "; decimal sales = 0m; Decimal.TryParse(salesString, out sales); // sales is 0

40 Conversion statements that use the Convert class
decimal subtotal=Convert.ToDecimal(txtSubtotal.Text);//string to decimal int years = Convert.ToInt32(txtYears.Text); // string to int txtSubtotal.Text = Convert.ToString(subtotal); // decimal to string int subtotalInt = Convert.ToInt32(subtotal); // decimal to int

41 Some Conversion Notes If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse(). If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters in invalid input. Convert.ToInt32() takes an object as its argument, it invokes Int32.TryParse() when it finds that the object taken as the argument is a string. Convert.ToInt32() also does not throw ArgumentNullException when it's argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

42 Conversion Details The ToString, Parse, and TryParse methods are included in all of the data structures. In some situations where a string is expected, the compiler will automatically call the ToString method. The Convert class contains static methods for converting all of the built-in types. To see all of the methods of this class, you can look up the Convert class in online help.

43 Standard numeric formatting codes

44 How to use the ToString method to format a number

45 How to use the Format method of the String class to format a number

46 Format Details You can include a number after some of the numeric formatting codes to specify the number of decimal places in the result. If the numeric value contains more decimal places than are specified, the result will be rounded using standard rounding. If you don’t specify the number of decimal places, the default is 2. You can include a number after the D or d formatting code to specify the minimum number of digits in the result. If the integer has fewer digits than are specified, zeros are added to the beginning of the integer. You can use the Format method of the String class to format two or more values.

47 Scopes The scope of a variable is determined by where you declare it, and the scope determines what code can access the variable. If, for example, you declare a variable within an event handler, the variable has method scope because an event handler is a method. In that case, the variable can only be referred to by statements within that method. Often, though, you want all of the methods of a form to have access to a variable. Then, you must declare the variable within the class for the form, but outside all of the methods. In that case, the variable has class scope and can be called a class variable. The other reason for using variables with class scope is to retain data after a method finishes executing. This has to do with the lifetime of a variable. In particular, a method variable is available only while the method is executing. When the method finishes, the variable is no longer available and the data is lost. Then, when the method is executed the next time, the method variables are declared and initialized again. In contrast, a class variable lasts until the instance of the class is terminated. For a form, that happens when you exit the form and the form is closed. As a result, class variables can be used for accumulating values like invoice totals.

48 Scopes Example

49 Scope:: One more time: How to work with scope
The scope of a variable determines what code has access to it. If you try to refer to a variable outside of its scope, it will cause a build error. The scope of a variable is determined by where you declare it. If you declare a variable within a method, it has method scope. If you declare a variable within a class but not within a method, it has class scope. A variable with method scope can only be referred to by statements within that method. A variable with class scope can be referred to by all of the methods in the class. The lifetime of a variable is the period of time that it’s available for use. A variable with method scope is only available while the method is executing. A variable with class scope is available while the class is instantiated.

50 Some of the constants in the FormBorderStyle enumeration

51 The syntax for declaring an enumeration
enum EnumerationName [: type] { ConstantName1 [= value][, ConstantName2 [= value]]... } Ex.: An enumeration that sets the constant values to 0, 1, and 2 enum Terms { Net30Days, Net60Days, Net90Days } An enumeration that sets the constant values to 30, 60, and 90 enum TermValues : short { Net30Days = 30, Net60Days = 60, Net90Days = 90 }

52 Statements that use these enumerations
Terms t = Terms.Net30Days; int i = (int) Terms.Net30Days; // i is 0 int i = (int) TermValues.Net60Days; // i is 60 string s = Terms.Net30Days.ToString(); // s is //"Net30Days" enum Terms { Net30Days, Net60Days, Net90Days }

53 Enumeration Details An enumeration defines a set of related constants. Each constant is known as a member of the enumeration. By default, an enumeration uses the int type and sets the first constant to 0, the second to 1, and so on. To use one of the other integer data types, you can code a colon after the enumeration name followed by the data type. To specify other values for the constants, you can code an equal sign after the constant name followed by the integer value.

54 How to declare a value type that can contain null values
int? quantity; quantity = null; quantity = 0; quantity = 20; decimal? salesTotal = null; bool? isValid = null; Terms? paymentTerm = null; // string? message = null; // not necessary or allowed

55 Two properties for working with nullable types
How to check if a nullable type contains a value bool hasValue = quantity.HasValue; How to use the null-coalescing operator to assign a default value int qty = quantity ?? -1; How to use nullable types in arithmetic expressions decimal? sales1 = m; decimal? sales2 = null; decimal? salesTotal = sales1 + sales2; // result = null

56 Nullable Details A nullable type is a value type that can store a null value. Null values are typically used to indicate that the value of the variable is unknown. To declare a nullable type, code a question mark (?) immediately after the keyword for the value type. The null - coalescing Operator (??) returns the value of the left operand if it isn’t null or the right operand if it is. If you use a variable with a nullable type in an arithmetic expression and the value of the variable is null, the result of the arithmetic expression is always null. You can only declare value types as nullable types. However, because reference types (such as strings) can store null values by default, there’s no need to declare reference types as nullable, and your code won’t compile if you try to do that.

57 The Invoice Total form

58 The controls that are referred to in the code

59 The event handlers for the Invoice Total form
private void btnCalculate_Click(object sender, EventArgs e) { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = .25m; decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount; txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); txtSubtotal.Focus(); } private void btnExit_Click(object sender, EventArgs e) this.Close();

60 The enhanced Invoice Total form

61 The code for the class variables and two event handlers
int numberOfInvoices = 0; decimal totalOfInvoices = 0m; decimal invoiceAverage = 0m; private void btnCalculate_Click(object sender, EventArgs e) { decimal subtotal = Convert.ToDecimal(txtEnterSubtotal.Text); decimal discountPercent = .25m; decimal discountAmount = Math.Round(subtotal * discountPercent, 2); decimal invoiceTotal = subtotal - discountAmount; txtSubtotal.Text = subtotal.ToString("c"); txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); numberOfInvoices++; totalOfInvoices += invoiceTotal; invoiceAverage = totalOfInvoices / numberOfInvoices; txtNumberOfInvoices.Text = numberOfInvoices.ToString(); txtTotalOfInvoices.Text = totalOfInvoices.ToString("c"); txtInvoiceAverage.Text = invoiceAverage.ToString("c");

62 The class variables and event handlers (cont.)

63 Extra 4-1 Calculate area and perimeter

64 Extra 4-2 Accumulate test score data


Download ppt "Based on Murach’s Chapter 4"

Similar presentations


Ads by Google