lecture 11: programming tami meredith. classroom vs. reality the things we teach are meant to allow...

43
CSCI1226 Introduction to Computing Science and Programming Lecture 11: Programming Tami Meredith

Upload: everett-baldwin

Post on 18-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

CSCI1226Introduction to Computing Science and Programming Lecture 11: Programming Tami MeredithClassroom vs. RealityThe things we teach are meant to allow you to transition to using your skills in real-world settingsBad habits are hard to correct after they have been developed, e.g., coding without planning/designMistakes in software can cause loss of human life or billions of dollarsWant to impress upon you the need to develop the discipline needed to produce high quality software (even just small tools for your own use)The ART of ProgrammingWriting a good program is more art than scienceProgramming requires:Structuring the dataSelecting/designing algorithmsUsing a PL (i.e., Java) effectively to implement 1. and 2.Testing and debugging the program (often half the work)!NOTE that "using Java" is only a small part of the process and is NOT "programming"Software EngineeringEngineering: Commercial development of a productSoftware: Computer ApplicationsGoals:Minimise RisksEnsure financial viabilityMinimise faults (including bugs)Many different development processes existThe later a fault/bug is found, the more expensive it is to repair!Famous Moments in Software Engineering

Development ProcessesSpecifications What do users need?Requirements What should the program do?Architecture/Design How should it be structured?Coding Making the design realTestingDeploymentMaintenance and Evolution (90% of work/profit)Note: All steps are not equal!Requirements and SpecificationsRequirements analysis determines what the end product must achieveProcess can take months or (in some cases) yearsNeed to know the goals (identify the problem to solve) before we can do anything elseSpecifications add detail and determine the basics of what the software will actually doCoding/PL is usually not considered in the slightestReal-world problems are difficult to understand and it can take years to fully comprehend them (if possible)E.g., U.S. cannot duplicate Netfile because their tax system is far too complicated for anyone to actually describe!Requirements = UnderstandingProfessionals spend a lot of time and money exploring the problem spaceWe want you to perform this step now, even when the problems are trivialExperience shows that students get overly fixated on learning "Java" and become poor programmers because they confuse programming with coding (i.e., translation of an idea into a PL)

Design and ArchitectureGood programs are designed before any coding is performedSome tools are:UML Unified Modelling LanguageUse-Case ScenariosFlow charts, event diagrams, etc.Pseudo-codePrototypesA reference architecture is created to provide a plan, just like blueprints guide construction projects

Trial and ErrorIt is possible to simply "try stuff" on the computer until you see something that looks rightGenerally done when you don't have a plan!Such "playing around" doesn't help you learn how to programGetting the program to work correctly is only of benefit when you know WHY it works!Only experiment to learn "Why" not to figure out the "How"Trial and error programming is also known (to professors) as "Guess and Failure" programmingData StructuresMany existBuilt using language primitivesSome examples:Arrays & StringsLists (Sort of like an array)Trees (Hierarchical structures)Graphs (Web structures)Stacks (LIFO), Queues (FIFO)Hash Tables (Key-based table management)Tables & Records (Database Models)Mathematics: Matrices, Coordinates, VectorsDomain-Specific Models: Banking, Finance, Physics, BiologyPrimitive Data Typesbyte, short, int, longValues without a decimal point, ..., -1, 0, 1, 2, ...float, doubleValues with a decimal point, 3.14, .333, 99.9, ...charAlphabetic symbols, 'a', 'b', '%', ...booleanTruth values: true, falsevoidThe empty set, nothing, no valuesComplex/Composite TypesArraysOrdered, fixed length, groups of identically typed dataSecretly a kind of objectStrings Special type that is very like an array of charAlso a kind of objectClassesUser defined collections of other types and methodsAs an OOPL, Java relies heavily on the use of classesEnumerations (Special classes)Represent finite sets with a limited number of members

VariablesAn "instance" of a type is always stored somewhereWe use identifiers (names) to create variables (named memory locations) that store an instance of a typeAn instance has a value, unless it is uninitialisedint x = 7;bool[] same = new bool[4];Scanner s = new Scanner(System.in);String name = "Tami Meredith";= is an operator that assigns a value to a memory location, LHS is Location, RHS is Value

Data ManagementThe basis of data management is understanding data flow how data moves around memoryData must be in memory, it can't be anywhere else!We need to always know what is in every memory location, such as:A copy of a value in another locationA reference to some data in another locationNothing, the location is emptyWe also need to know the type of everything (i.e., how it is encoded and represented)E.g., "1" '1' 1 1.0f

ExerciseWrite a method named noVowels that makes a copy of a string with all the vowels removed Vowels are a, e, i, o, u (and sometimes y or w but don't remove them) E.g.:System.out.println(noVowels("Hi There Piggy!"));will print to the screen: H Thr Pggy!Solutionpublic static boolean isVowel(char c) { if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) { return (true); } return(false);}

public static String noVowels(String s) { String s1 = ""; for (int i = 0; i < s.length(); i++) { if (!isVowel(s.charAt(i)) s1 = s1 + s.charAt(i); } return(s1);}ScopeEverything with a name has a "scope"Scope is a fancy word that means "the places something can be accessed"a synonym for "visibility"The scope of a named entity is mostly dependent upon where it is defined (but other things can affect it)public and private are scope modifiersScope affects data-flowScopepublic class periscope { public static final int x = 0;

public static void two () { int x = 2; System.out.println(x); // prints 2 }

public static void main (String[] a) { // Different method, different scope int x = 1; System.out.println(x); // prints 1 two(); // prints 2 }} // end class periscopeClass Scopepublic class example { public static final int ONE = 1; public static int one () { return (ONE); } public static void main (String[] a) { // one is in the class so it is in scope int o = one(); System.out.println(o); }} // class ends, scope ends!PublicPublic is a scope modifierPublic really means:This entity can be used outside of this scope!Can only be assigned to members of a class!Staticmain() must be static (this is required)we can only have one copy of something that is staticif we had two mains, which one would we use?main (since it is static) can only call other static methods, UNLESS they are in a different classi.e., static prevents a method from accessing anything non-static that is in the same classThis is why all your methods (until now) are always staticThe "main" class (i.e., the class that contains main) should really only contain static methods for this reasonTo get around this limitation (which is actually a nuisance), we need to have other classesStatic is actually a pain, life would be better without it!

ProgrammingVariables/Data is our first thoughtWhat do we have to work with (i.e., starting point)?What do we have to keep track of while we are working?What must we finish with (i.e., the solution)?EVERYTHING can be put in memory even if it isn't neededLater, we can delete unneeded variables, if we have timeIts better to store too much and not use it than too little and not have it when we need itData Flow and ManagementMemory management: What is it stored?What is the storage location called?Type: How much memory is allocated? Scope: Where can it be used?Movement and replacement: When is it copied to another location? When is something copied over top of it?Modifiers: public, private, staticAlgorithmsA set of steps to accomplish the taskComposed of:statements: if, for, do, while, etc.expressions: =, -, ++, *, %, ...Statements and expressions can be grouped into blocks using { and }Blocks can be named to create methods, which accomplish some part of the algorithm, e.g., getGuess(), scoreGuess()

Choices "Conditionals"Choosing between alternative actions is accomplished using "if ..." or "if ... else ..."There is a secondary type of selection available using a switch statementExample: if (x < y) { System.out.println("X is less than y");}else{ System.out.println("X is NOT less than y");}Else-Ifif (x < y) { System.out.println("x < y");} else if (x == y) { System.out.println("x equals y");else { System.out.println("x > y");}

// SAME AS ...

if (x < y) { System.out.println("x < y");} else { if (x == y) { System.out.println("x equals y"); else { System.out.println("x > y"); }}

RepetitionWe often do things more than once"Get four integers from the user"How do we code this?int i1 = keyboard.nextInt();int i2 = keyboard.nextInt();int i3 = keyboard.nextInt();int i4 = keyboard.nextInt();Hmmm, looks like a loop from 1 to 4int[] i = new int[4];for (int index = 1; index 0; i = i - 1) { System.out.print(s.charAt(i));}System.out.print("\n");

Trial and Error = ?To DoGo to the lab and complete Assignment 10 THE LAST ONE!Re-read Chapters 1 through 7 one more timeAt this point you should understand almost all of Chapters 1-7 (except the graphics supplements) and a few parts of chapter 6Program, program, program! Redo exercises from the classes until you truly understand what you are doingQ. How do I know when I understand?A. When you can type it into a computer and it works the first time (except for the occasional typographic error)