1 / 43

COP 3530 – C# Programming

COP 3530 – C# Programming. Chapter 5 – Jan 28, 2015. Before Class. Stick in your thumb drive Start Up VS 2012 Create a new solution called Lecture5. Get the Lesson5.txt file from out web side and stick it in the Program.cs of the Lecture5 project. Announcements.

bowlesc
Télécharger la présentation

COP 3530 – C# Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COP 3530 – C# Programming Chapter 5 – Jan 28, 2015

  2. Before Class • Stick in your thumb drive • Start Up VS 2012 • Create a new solution called Lecture5. • Get the Lesson5.txt file from out web side and stick it in the Program.cs of the Lecture5 project.

  3. Announcements • We’re Skipping Chapter 4 for a couple of weeks. • Let’s go over possible solutions to Assignment 1.

  4. A Couple Of Other Notes on Methods • The Parameters into methods can be either “by reference” or “by value” or “out” • The default for normal variables is “by value” • What this means is that when the method starts up, a new variable with the name of the parameter is created, and the value of the calling variable is passed into the method. • The method can play around with the parameter within itself, but no changes are made to the original variable • If the parameter is set up as “ref”, the variable MUST be initialized and the ADDRESS of the variable is passed in, and the method can change the value (since it is working with the same memory space) • If the parameter is set up as “out”, then the ADDRESS of the variable is passed in, and the method can change the value (since it is working with the same memory space), but it does NOT have to be initialized. • Let’s go look.

  5. Programming Language Basics • A way to store and retrieve information to and from memory. • A way to compute basic mathematics and store results • A way to communicate with the "outside world" • A way to compare information and take action based on the comparison • A way to iterate a process multiple times • A way to reuse components.

  6. What have we been doing • Simple "sequential" programs • The program starts at the beginning and goes to the end. • No choices, branches, decisions, just top to bottom

  7. Control Structures - Selection • Tonight we introduce condition statements • Statements that evaluate an expression and then perform one action if the expression is true and another if the expression is false • The main way of doing this is with an "if" statement • Some Examples (in pseudo code) • If hours is not equal to 0 then The employee’s Hourly_Rate is Gross_Pass / hours • If hours less than or equal to 40 then Employee_Pay = Hourly_Rate * Hours Otherwise Employee_Pay = Hourly_Rate * Hours • If weather is raining then Take your umbrella with you

  8. Logical Boolean Expressions Relational Operators • A "logical Boolean expression" is a C# statement that has a value of either true or false • Boolean Expressions compare two or more variables/objects and determine the relationship between the variable. • Comparisons are based on relational operators: • == equals != not equal • < less than <= less than or equal • > greater than >= greater than or equal • Notice that "equal to" is TWO equal signs • a = b is as assignment statement. The value of b is stored in address b. • a == b is a conditional statement. If a is the same as b, the statement evaluates to true otherwise false • The book thinks that <= and >= are evil. I don’t

  9. Logical Boolean Expressions Simple Data Types - Integers • Numbers are pretty straight forward • 5 < 7 ? • 3+3 != 12/2 ? • 2.5 > 5.8 ? • 5.9 <= 7.5 +2 ? • Notice a Boolean Expression can have other expressions (arithmetic for example) embedded within the expression. • Also notice that one can have expressions on either side (or both sides) of the equation. • We’ll talk about float numbers in a little bit. You have to be careful!!

  10. Logical Boolean Expressions Simple Data Types - Char • Comparison of Char values is done based on the Unicode value of the character. • For the United States, this will really match the ASCII character codes. • Notice that lower case letters are "greater than" upper case letters!! • Also realize that the CHAR of a number is way different than the number itself • ‘8’ == 8 ? • This will be allowed since (remember) we can do math with chars, but what is the result?

  11. ASCII Character Chart

  12. Logical Boolean Expressions Strings • Strings are compared character by character using the ASCII/Unicode codes we just looked at. • The only direct operator available though is "==". As soon as there is a difference between the two strings, that character is going to determine the logical relationship between the two strings. • "Bee" == "Before" ?? • The determination is made on the third character. "e" Not = "f" • What About "BEFORE" and "Before"??

  13. Logical Boolean Expressions Strings • To determine if one string is "Greater Than" another, they wrote a static method called String.Compare • int nCompare = String.Compare("Be","Before") • String.Compare returns 0 if the two strings are the same, 1 if string1 is "bigger than" string 2, and -1 if string1 is "less than" string 2 • When one string is a substring of another starting with the left character, the longer substring is "greater than" the shorter one. • This whole mess of "greater" or "less" probably doesn’t make sense when playing with Strings, but who knows.

  14. Logical Boolean Operators • Logical Expressions can be connected together with Logical Operators. • ! is not – reverse the Boolean value of an expression (unary operator) • && is and – The entire expression is true if and only if both sides of the && are true • (a > b) && (a > c) implies than • Both b and c are less than a • What does (a >b) && (a==b) imply? • || is or – The entire expression is true if the left side is true or the right side is true • (a > b) || (a > c) implies that • a is greater than b or a is greater than c or a is greater than both of them

  15. New Order of Precedencewith Logical Operators • Unary operators (- + ! ++ --) • Multiplication/Division (/ * %) • Addition/Subtraction (+ -) • Relational GT/LT(< <= > >=) • Relational Equals (== !=) • And (&&) • Or (||) • Assignment (=) • What takes precedence over all of these?? • If you have operators in the same order, what is done first? • What happens with multiple "=". • This is a weird one. Multiple = are computed RIGHT TO LEFT!!

  16. Logical Boolean Operators • Logical and Arithmetic Operators can appear in the same statement and are then evaluated based on the order of precedence • Unlike C and C++, Numbers and Char variables cannot appear in statements with logical operators. This is due to the fact that C# assigns the value of a Boolean as either True or False while C and C++ use 1 and 0.

  17. bool found =true; int age = 20; double hours = 45.30; double overTime = 15.00; int count = 20; char ch = 'B‘; !found hours > 40.00 !age !found && (age >= 18) !(found && (age >= 18)) (ch == ‘C’) || (int == 0) hours + overTime <= 75.00 (count >= 0) && (count <= 100) ('A' <= ch && ch <= 'Z') (ch == ‘C’) && (int == 20) Let’s play some

  18. Just to make sure we are clear • All this stuff we just went through can be used in assignment expressions. • We talked before that • If any float is involved in an expression, then it is going to a float at the end. • The only way an integer is going to be returned is if ALL the variables and constants are an integer. • Now we have a new rule • If a logical operator is used anywhere in the expression, and the statement does not cause a syntax error, the statement will return either true or false

  19. OK – Enough Preliminary Stuff • The syntax for "if" statements in C# is: • if (logical boolean expression) • { • C# commands • } • Else • { • More C# Commands • { • A "logical Boolean expression" is a C# statement that has a value of either true or false.

  20. Let’s Look At The Simple Case int nScore = 85; char sGrade = ‘F’; if (nScore > 79) sGrade = ‘B’; Console.Writeline ("Your Grade Is: {0}",sGrade); In this case, the boolean expression is nScore > 79 once the comparison is done, either a value of true or false will be returned. If the value is true, the next statement is executed. If it is false, the next statement will be skipped.

  21. Now that you’ve seen the basics….Never do that again. int nScore = 85; char sGrade = ‘F’; if (nScore > 79) sGrade = ‘B’; Console.Writeline ("Your Grade Is: {0}",sGrade); • What’s wrong??? • Bradley vs. the Book. The book is quite happy with this syntax, Bradley is not. • What follows an if statement can be one statement or a group of statements. • ALWAYS CODE YOUR ifs LIKE WHAT IS GOING TO FOLLOW IS A GROUP OF STATEMENTS!!!

  22. Instead, do this int nScore = 85; char sGrade = ‘F’; if (nScore > 79) { sGrade = ‘B’; } Console.Writeline ("Your Grade Is: {0}",sGrade); • And why do I care. With the above statement I am only doing one thing. Let’s say that I am asked to also add 1 to the number of Bs given. Let’s go back to the other way (without the curly braces)

  23. And this is why….. int nScore = 85; char sGrade = ‘F’; int nNumber_of_Bs = 0; if (nScore > 79) sGrade = ‘B’; nNumber_of_Bs = nNumber_of_Bs + 1; Console.Writeline ("Your Grade Is: {0}",sGrade); So, what happened here??

  24. OK – No More ranting and raving • BUT YOU WILL ALWAYS USED THE CURLY BRACES EVEN IF IT IS ONLY ONE STATEMENT ON AN if!!! • As shown in the original example, an "if" can have an "else" • Let’s change our little program to pass/fail

  25. if…..else int nScore = 85; char sGrade; int nNumber_of_Ps = 0; int nNumber_of_Fs = 0; if (nScore >= 70) { sGrade = ‘P’; nNumber_of_Ps = nNumber_of_Ps + 1; Console.Writeline ("WOOHOO…You Passed!!"); } else { sGgrade = ‘F’; nNumber_of_Fs = nNumber_of_Fs + 1; Console.Writeline (" Oh Well – You FAILED!!"); }

  26. if (nBalance > 50000.00) {nInterestRate = 0.07; } else if (nBalance >= 25000.00) {nInterestRate = 0.05; } else if (nBalance >= 1000.00) {nInterestRate = 0.03;} else {nInterestRate = 0.00; } if (nBalance > 50000.00) {nInterestRate = 0.07; } else if (nBalance >= 25000.00) {nInterestRate = 0.05; } else if (nBalance >= 1000.00) {nInterestRate = 0.03;} else {nInterestRate = 0.00; } if..else vs. if..else if..else Both series of statements do exactly the same thing, but the one on the right is easier to read and understand with less indentation.

  27. A Dangling Else const int nVERY_RICH = 1000000; const int nKINDA_RICH = 100000; int nSalary; Console.WriteLine( "Enter Your Salary: "); String sSalary = Console.Readline(); nSalary = int.Parse(sSalary); if (nSalary > nKINDA_RICH) if (nSalary > VERY_RICH) { Console.WriteLine ("I hear you\'re very rich"); } else { Console.WriteLine ("I hear you\'re poor"); } What happens when we run this. What is wrong with the semantics?

  28. Another issue of semantics. const int nVERY_RICH = 1000000; const int nKINDA_RICH = 100000; int nSalary; Console.WriteLine( "Enter Your Salary: "); String sSalary = Console.Readline(); nSalary = int.Parse(sSalary); if (nSsalary > KINDA_RICH) { Console.WriteLine ("I hear you\’re kinda rich"); } else if (salary > VERY_RICH) {Console.WriteLine ("I hear you\'re very rich"); } else { Console.WriteLine ("I hear you\'re poor"); } • What’s wrong with the above??

  29. What About FloatsChecking for Tolerance • As we have seen, floating point numbers may not be always actually "be" what they "seem" • unlike integers, one may want to consider a tolerance for when one can say that two floats are the "same". • For example, if we are dealing with money, maybe we can say that two floats (X AND Y) are the same if their difference is less than .0001 • if (Math.Abs(x - y) < 0.0001) • Math.Abs is the absolute value method, not something to do with my almost six pack!!

  30. Don’t Think You Can Do This • One may be tempted to write an if statement like this: if (0 <= num <= 10) { Console.WriteLine ("{0} is within range of 0 to 10", num); } else { Console.WriteLine ("{0} is NOT within range of 0 to 10", num); } • The Correct Syntax is: if ((0 <= num) && (num <= 10)) • What About this? if ((0 <= num) !! (num <= 10))

  31. One More Time = does not equal == • Just to make sure you get this • = is used for assignment • == is used for comparison • You will screw this up at least 10 times before getting it right!!

  32. Switch Statement(Another way to do if…else if) • Allows one to assign an action to separate values of variable • Includes a default case used when none of the other cases are appropriate.

  33. Basic switch statement switch (expression) { case value1; statements case value 2; statements case value n; statements default; statements } • Although multiple statements can be placed after each case statement without requiring curly braces, each case statement must end with the break command OR the next command will also be executed until a break is hit.

  34. switch (nGradePoints/10) { case 0: case 1: case 2: case 3: case 4: case 5: Console.WriteLine ("You Failed"); break; case 6: Console.WriteLine ("gotta D"); break; case 7: Console.WriteLine ("gotta C"); break; case 8: Console.WriteLine("gotta B"); break; case 9: case 10: Console.WriteLine("gotta A"); break; default: Console.WriteLine ("bad grade"); break; } Typical switch command

  35. The switch expression can be • an integer • a char • a String • a boolean • but check for values of true or false in the case statements • probably really doesn’t make sense to switch on this • an expression that resolves to one of these

  36. TryParse • Now that we understand conditionals, let’s visit our old friend the Parse method: • There is a second method called TryParse, that you can call. Instead of returning a converted number (or blowing up the program!!), it returns a boolean to say whether or not the conversion worked. • Let’s play with this.

  37. A Word About a Variable’s Scope • A variable “lives” in the curly braces in which it was created and “dies” when the flow of control goes beyond those curly braces. • Once a variable is defined at a parent level, C# will not allow a child block to have a variable declared with the same name • Let’s play with this some.

  38. File I/O (From Chapter 13) • We’ve played around with reading from and writing to the console, but it gets old having to reenter stuff over and over • Near the end of this class we’ll go into using a database to hold stuff, but for now we’re going to play around with writing to and reading from a file.

  39. StreamWriter and StreamReader • C# makes use of two classes that are part of the System.IO library • StreamWriter has the ability to write information out to a file on disk. • StreamReader has the ability to read information in from disk.

  40. StreamWriter • To write information to a file, we first need to associate it with a variable in our program: • String sFileName = "DemoFile.txt"; • StreamWriter ioOutFile = new StreamWriter(sFilename); • A word about the new crap • Once we have it created, we write to it just like we would to the console, except instead of using the noun "Console" we use the name we gave the stream: • ioOutFile.WriteLine("{0} {1}","One","Two"); • ioOutFile.WriteLine("{0} {2}","Three","Four"); • ioOutFile.WriteLine("{0} {3}","Five","Six"); • When you are done writing you close the file: • ioOutFile.Close(); • Let’s do this and see what happens.

  41. StreamReader • Once a file exists, one can open it and read it in. Unfortunately, C# doesn’t have a nice input conversion ability like C and C++ • String sFileName = "DemoFile.txt"; • StreamReader ioInFile = new StreamReader(sFilename); • Let’s just read the file in that we just made and display it on the Console: String sInLine; while ((sInLine = ioInFile.ReadLine()) != null) { Console.WriteLine(sInLIne); } ioInFile.Close() • We just introduced a loop. We’ll cover this in a lot more detail next week. • Let’s pull this over and run it to see what happens. • Let’s see where the program is putting the file.

  42. Decoding What Is In The sInLine • So, we can read in each line, but in our example, each line has two fields separated by a space. • We can use the SubString and IndexOf methods of the String class to split the one string into two • Another approach would have been to make the information written to out file column specific. • A third way uses another method called “Split()” that we will cover once we go over arrays. • Let’s Use SubString and IndexOf • Let’s redo the whole thing with columnized output

  43. Assignment 2 • Due in Two Pieces • Parts 1 & 2 are due Monday, Sep 28 by 11:59 PM • Part 3 is due Friday, Oct 2 by 11:59 PM • You may turn in the assignments early, and I will review and let you know of any issues • EXCEPT – I will be gone from Sept 24 until Sept 28 and will not have any internet access, so get your questions in early for Parts 1 and 2!!

More Related