lecture 3: branching tami meredith. roadmap brief review of last class oop and methods: using the...

50
CSCI1226 Introduction to Computing Science and Programming Lecture 3: Branching Tami Meredith

Upload: shannon-dennis

Post on 18-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

CSCI1226Introduction to Computing Science and Programming Lecture 3: Branching Tami MeredithRoadmapBrief Review of last classOOP and Methods: using the library proceduresStrings Revisited: A useful Class/Data TypeBranching: Simple non-sequential control flow

AssignmentsAssignments are intended to be done in the labsTheir purpose is to provide an overview of the skills you will need to masterThe assignments are NOT enough for some of youAssignment 1 simply presented a few skills LOTS more REPETITION is needed to become competent

Comments in JavaOne line comments// starts a one line commentEverything from the // to the END of the line is ignored e.g., // Written by Tami clock = 2.95; // CPU speed in GHzMulti-line comments/* begins a multi-line comment*/ ends a multi-line commente.g., /* Author: Tami Meredith Date: September 26, 2011 */

Data TypesIntegers: byte , short, int, long (8, 16, 32, 64 bits , or 1, 2, 4, 8 bytes each)e.g., -10, -1, 0, 1, 100, 23456789654Floating Point: float, doublee.g., 3.14, 0.19, 22.0Characters: char (Unicode)e.g., 'a', 'b', 'A', 'B', '_', '$', ...Booleans: boolean, Created by tests, used to make decisionse.g., true, false (and nothing else!)Representation vs. MeaningEach type has a different representationWe, as humans, may interpret the value of a type and apply meaningApplying similar meanings does not mean that the values are similar1.0 1 '1' "1"All mean "one"But they are not represented the same in memory

OperatorsStandard math: +, -, *, /Modulus (Remainder): %Assignment to a variable name uses =Can change the type of something using a castint x = 1;float y = (float) x;+ is also string concatenatione.g., "Hi " + "there" creates "Hi there"

Changing TypesComputers like everything to be the sameAdding 2 ints, concatenating two stringsWill convert something into a different type so they are the same this is "coercion"LOTS of rules about when coercion occursAvoid learning them by always casting (changing types) yourselfBasic Data Managementfloat avg; // Calculated mean scoreint cnt = 4; // Count: number of scores (a constant)

int score1, score2, score3, score4;

/* Record the scores obtained */score1 = 72;score2 = 12;score3 = 66;score4 = 99;

/* Calculate the average (fails because of coercion) */avg = (score1 + score2 + score3 + score4) / cnt;

/* Display the result */System.out.println("The mean is " + (string) avg);

Our First Example (revisited)// First Example// By Tami Meredith

/* Define "program" class called hello in the file hello.java */public class hello {

/* Define the method main for the program */public static void main (String[] args) {

/* Use the method println() */System.out.println("Hello! Welcome to CSCI1226.");

} // end main()

} // end class helloExerciseWrite a complete and correct Java program that will convert a temperature in Celcius into a temperature in FahrenheitThe initial temperature should be stored in a variable named tempThe formula is: F = (9/5 * C) + 32 The result should be printed to the screenSolution// Temperature Converter// By Tami Meredith

public class ctof {

public static void main (String[] args) {

float temp = 12.0f; float fahr = ((9.0f/5.0f) * temp) + 32.0f; System.out.println(temp + " degrees C is " + fahr + " degrees F");} // end main()

} // end class ctofConstantsA value in the code is called a constant or literalIt is constant because it does not change when the program is executed it must be changed by editingA named constant is a constant that is given a name and for which the value does not change when the program is executed

public static final int RADIX= 8;x = 2 * RADIX;System.out.println("Hello");Filling in GapsWe've been putting magic words in our program to make them work e.g., public, static, void, class, importNow we will start to learn what some of these words meanHopefully some of the confusing parts of our programs will start to make a little more senseBUT DON'T PANIC if you are still confused (I got confused trying to make the slides )The Empty TypeSometimes we want to specify that something doesn't existE.g., in Java all methods specify what they produce , but some methods don't produce anything and have to indicate this factWe use the void type to specify something has no value or won't existvoid represents an empty setIt is a type with no valuesObject Oriented ProgrammingOften abbreviated OOPCame into vogue in the 90s but was first presented in the language Simula 67One way of thinking about data, but not the only wayJava requires the use of OOP (we have no choice)Problem: To understand objects and classes one needs to understand simpler concepts such as procedures or subroutines, BUT, we can't learn these without using objects and classes! (Stop the bus, I want to get off ...)This is why we ignored public, static, class etc.Another Look at OOPmyprogram.javaclass myprogram class System(contains)outclassPrintWritermethod mainOthermethods...method printlnOtherclassesOOP: SummaryMethods perform actionsClasses group methods and dataObjects are classes that have been given memory (instantiated) so they can store dataEvery program has one class (in program.java)The "program" class has a method called main

MethodsA method in OOP is (almost) the same as a procedure, routine, or function in other programming languagesEvery Java program has at least one method (called main) and may have othersMethods perform some set of steps on some group of dataBig programs with lots of steps are broken down into smaller parts and each part is put into its own methodMethods are like "Lego Blocks" of programming

Using MethodsMethods require they be given data to useThis data is referred to as the method's parameters or argumentsMethods are either:created (defined) by the programmerimported from a libraryExamples of methods:println(), print(), main()Methods do work, they accomplish a task or a part of a taskMethods (or functions/procedures/subroutines) are one of the KEY concepts in programmingReturn TypesMethods do things such as print characters to the screenMethods also produce things so they can be used in an assignment statementWhat a method produces is called its "return value"Methods can only produce (i.e., return) one thingThe return value can be used in an assignment but the other things the method does cannot and thus are called "side effects"Method Definition (Again)public static void main (String[] args) { ... }

public: there are no restrictions on who can use this method (the opposite is private)static: this method is not related to any specific set of data, no object must be instantiated if we want to use this methodvoid: the method returns nothing, it cannot be used in an assignment statementmain: the method is named main(String[] args): the method must be given a list (array, []) of Strings to work with (these are the parameters or arguments) we named this list of Strings as args{ ... }: the Body of the method where we put code that does workpublic class multimethods {

/* Define a method to print something */ public static void printname () { System.out.println("My name is Tami."); }

/* Define a method that returns something */ public static int makezero () { return (0); }

/* Define the method main for the program */ public static void main (String[] args) { int zero; /* Use the methods we defined */ printname(); zero = makezero(); System.out.println("makezero returns " + zero); } // end main()

} // end class multimethodsCalling MethodsWe've seen:printname();name.length(); where name is variable of type StringSystem.out.println("stuff");

Why do they differ?

When a method needs to access data, we have to specify what data to access. In this case we tell it to access the String stored in nameWe will come back to this more in another lectureI wish Java was easier and less complex Sorry!Enough already ...By now, your brains are full ...Full brains explode (which can make zombies happy)Cleaning the classroom is expensiveTo save money and Lysol we will take a break now ...

How to program with OOPFigure out what the program is called, e.g., addstuffCreate a file called addstuff.javaIn addstuff.java create a class called addstuffIn class addstuff, create a method called mainMake main public so everyone can use it (it is required that main is public)Make main static so that we can use main without needing to instantiate the class (this is also required)NOTE: static methods are special cases and are not the normal way we do things!InstantiationA class is a grouping of data and methodsWhen we define a class, we are simply describing what it looks like and what it doesWhen we instantiate a class and create an object, we are giving it memory space to store its dataA class is like a type, it just describes somethingAn object is like a variable, it stores the group of data described in the classstatic means we can use something without instantiating the class (creating an object) because we don't need the dataProgramming Process (Technical)TextEditorCompiler(javac)Interpreter (JVM: java)UserLibrariesOperating System (Windows)OutputInputJDKClicking "Run"program.java is in the editor windowjavac is invoked to create program.classthe jvm is startedSystem.out, System.in, System.err are opened (the System "class" is "instantiated" as part of the jvm), the Runtime class is instantiated program.class is loadedmain is called and values for args are providedthe program executes until it endsSystem and Runtime are deletedcontrol is given back to JCreator

Types vs. Valuesint x = 3;String s = "Hello";3 and "Hello" are values (and literals)int and String are typesx and s are instances of the type that hold values (e.g., variables)A class is also a typeThe computer stores an instance of the class containing main for us!Uses the name of the file we execute to determine what to make an instance of (looks for a class with the same name)StringsStrings are a special class in JavaThey are different to other classes because strings are such a common and important kind of dataA String is an ordered (sequential) set of charactersA String can have 0 to billions of charactersIn practice, Strings longer than a line or two are a bad ideaString constants (literals) are simply defined using double quotes"Hello World!", "Resistance is fertile", "a", and "" are all stringsIndicesStrings are indexed so we can refer to and examine each character in themThe index is the offset from the beginning of the StringSo, the characters in a String are numbered 0, 1, 2, 3, ...First index is zeroLast index = length - 1String"Hello!"Index012345String MethodsSee Figure 2.5 in the text (page 86)length() returns the length of a string (as an integer)indexOf(string2) returns the index of string2 in string or -1 if string2 is contained in stringequals(string2) returns true if string equals string2 otherwise it returns falseString sentence = "Hello programming class";int len = sentence.length();boolean same = sentence.equals("Good bye!");

ExerciseThe String method charAt(i) returns the character that is located at index value iWrite a program that has one string called name, which stores your name and that will print out the first character of your nameSolution// First Initial Exercise// By Tami Meredith

public class first {

public static void main (String[] args) {

String name = "Tami Meredith"; char init = name.charAt(0); System.out.println("The first initial of " + name + " is " + init);} // end main()

} // end class firstControl FlowUntil now all programs have been sequentialWe do the instructions one after another without skipping or jumping over anyThis is the default flow of executionThis is really boring and very limitingNeed a way to say, "lets only do ... when ... occurs", or "do this .... if .... happens and do .... otherwise"Going to explore conditional statements to achieve this (Chapter 3)!Control FlowFour Basic ConceptsSequential: go to the next lineBranch: make a choice between two branches based on some conditionE.g., if raining then take umbrella else leave at homeLoop: Do something a set number of timesCall a Method: Ask a method to do something for us and go to its code. Come back to where we were when its done.PseudoCode (A Helpful Tool)Something like Java, but it wont actually executeUsed to structure our thinking and solutions

method go-out {isRaining = call checkWeather;if (isRaining)gear = umbrella;elsegear = nothing;}TestsTests compare things and generate the boolean value of true or falseYou have seen tests before in mathematics3 < 4 is a test that returns true4 < 3 is a test that returns falseThere are 6 kinds of numeric comparison, =, ==, !== means assignment, == is the equality test (you will mess this up forever we all do, its frustrating)

Other Testsmethods that return a boolean, such as equals, can be used as a test

String str1 = "one";String str2 = "1";// = means assignment // b can be used where a test is neededboolean b = str1.equals(str2);Using a test - BRANCHINGWe have the "if" statement in Java to use testsif (test) true-actions else false-actions

Example:int n1 = 3;int n2 = 4;if (n1 < n2) System.out.println("N1 is smaller");else System.out.println("N2 is equal or smaller");Alternative Formatif (test) true-actionsNo "else" part in this versionExample:int n1 = 3;int n2 = 4;int result = 1;if (n1 != 0) result = n2 / n1;System.out.println("Quotient is " + result);BlocksWe can group a set of statements that we wish to perform Such a group is called a "Block"Blocks are identified with { and }We have used blocks in methods and classesBlocks can be used other placesBlocks in Actionint n1 = 3; n2 = 4;int result;

if (n1 != 0) // Situation A result = n2 / n1; // indenting next statement does not put it inside the if System.out.println("Quotient is " + result);

if (n1 != 0) { // Situation B Same as Situation A result = n2 / n1;}System.out.println("Quotient is " + result);

if (n1 != 0) { // Situation C result = n2 / n1; System.out.println("Quotient is " + result);}

Style PointsThings inside a block should be indentedIndenting indicates that something is in a block, it does not CAUSE it to be part of the blockBlocks should be used liberallyBlocks have no detrimental impacts on performanceLike parentheses, blocks add clarity and make code more understandableBoolean AlgebraSpecial operators exist to connect testsThat is, what if we want to test if a variable is between 10 and 20?Our test would be: "x >= 10" and "x