230 likes | 391 Views
COMP-2001. Lectures 1 & 2. Data structures & algorithms I (then in January: COMP-2006: DS&A II) Eleni Mangina / eleni.mangina@ucd.ie Course web: http://www.cs.ucd.ie/staff/emangina/COMP2001. Practicals. Sessions as assigned; attendance mandatory 10 practicals (nearly 1 per week)
E N D
COMP-2001 Lectures 1 & 2 • Data structures & algorithms I (then in January: COMP-2006: DS&A II) • Eleni Mangina / eleni.mangina@ucd.ie • Course web: http://www.cs.ucd.ie/staff/emangina/COMP2001
Practicals Sessions as assigned; attendance mandatory 10 practicals (nearly 1 per week) Each will probably require: 2-4 hours prior to your session 1.5 hours in lab 2 hours after session Several problems each, lifted directly from text-book Programming requires practice! 30% of total course mark!Examination will require you understand the practicals! 1 week late? Maximum of 50% > 1 week late? No marks earned
Practicals Don’t cheat Cooperation and group studying are encouraged. But it’s easy to detect, andCheating will be dealt with according to theDepartment’s harsh plagiarism policy.
Course outline • Java refresher (1 week) • Object-oriented and modular design (1 week) • Mathematical tools for analyzing programs (1 week) • Remaining 9 weeks on a variety of useful topics • Stacks • Queues • Lists • Vectors • Trees • Priority queues • Heaps • Topics relevant to all programming languages 2001 is not just a course on “more Java” A useful “bag of tools”that forms the foundationof all large software projects
Textbook • Goodrich & Tomassia -- Buy it!Many useful resources at book’s web site. • You Must read assigned sections before corresponding lecture! • Otherwise you’ll be lost
Java refresher • Forget Java over the summer? Try the COMP-2001 notes, or any of the excellent books or Web tutorials (see course Web for pointers) • For Thursday: Read G&T Chapter 1 • Start Practical #1 (due Friday 29/9 @ 5pm) • Some of the following details may be bewildering or overly complicated at first -- come back to these notes or resources later when you understand what’s going on
Basic Concepts • Classes: a conceptual “box” that holds data (“instance variables”) and methods that can be invoked in the data. • Objects: instances of a given class • Types: classes + primitive types (int, float, ...) + built-in data structures (array) • Methods: a.k.a. “functions”, “subroutines” • Access modifiers: public, private, static, … • Expressions: create new values from combinations of existing values • Control flow: if, for, return, ... • Packages: how classes are organized
Classes class Fish { int nfins; // instance String name; // variables Fish(int _nfins, String _name) { // constructor nfins = _nfins; // method name = _name; } void morefins(int delta) { // “regular” method nfins += delta; } }
A complete program • A Java program doesn’t “do anything” unless is contains a special main method: class Fish { int nfins; String name; Fish(int _nfins, String _name) { nfins = _nfins; name = _name; } void morefins(int delta) { nfins += delta; } public static void main(String args[]) { Fish f = new Fish(3, "Fred"); // object creation f.morefins(4); // method invocation System.out.println("Fred has " + f.nfins + "fins"); } }
Files, packages, classes • A single Java application typically comprises many classes, grouped into several packages, much of which might be shared with other applications: Human Resources Program Payroll Program package A package C package D C1 C5 C8 C2 C6 C9 C7 C3 C10 C4 package B
Files, packages, classes - continued • There must be a 1-to-1 correspondence between: Classes - Java source files Packages - directories comtaining the class files /app/acounting/packageA/C1.java /C2.java /packageB/C3.java /C4.java /sharedstuff/packageC/C5.java /C6.java /C7.java /human-res/packageD/C8.java /C9.java /C10.java
Creating objects and values type variablename = expression int nfingers = 4; double weight; // very occasionally, initial value inappropriate/unnessary boolean defective = weight<0; // initial value can be any expression Integer ntoes = new Integer(4); // primitive data types aren’t objects Boolean problem = new Boolean(defective || (nfingers<0); String name = "Bob"; Fish f = new Fish(3, "Bob");
Simple Input/Output • Java has an incredibly complicated hierarchy of classes for performing input/output. • Output System.out.println(f.name + " has " + f.nfins + " fins"); • Input import java.io.*; // enable access to all Java I/O classes … BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line = stdin.readLine(); // read 1 line of text Next step depends on what data type the user is expected to enter. For example… int xnfins = Integer.valueOf(line).intValue(); // expecting an integer … or … float weight = Float.valueOf(line).floatValue(); // expecting a float
Exceptions • Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static void main(String[] args) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.print("Enter the number of fins > "); // wait til user enters something other than just RETURN while ((line=stdin.readLine()) == null) ; int nfins = Integer.valueOf(line).intValue(); } catch (IOException x) { // oops -- something strange went wrong System.out.println("Is your keyboard OK?! -- " + x); } catch (NumberFormatException x) { // entered something like “frog” System.out.println("Integers only! -- " + x); } } }
Control flow if (nfins > 10) { // execute block only if condition holdsSystem.out.println(“Are you sure??!??!”); } int a = 10, b = 20; while (a>0) { // repeatedlyexecute body until a=0 b = b+a; if (b > 60) break; // immediately terminate while loop a = a-1; } // now a=5 and b=65 for (int i = 0; i < b; i++) { // set i=0, 1, 2, …, 64a++; // shorthand for “a = a+1” } // now a=70 (and b is still 65)
Expressions • float appendageCost = (nfins + ntoes) * costPerAppendage; • int remainder = numerator % divisor; // eg 5%2 = 1 • boolean probablySick = (whiteCellCount > 145); • x = ++j; // increment j, and set x to the new value • y = j++; // increment j, and set y to the current value • String fullname = firstname + "" + surname; • double w = 45; // set w to the real number 45.0 • int x = 45; // set x to the integer 45 • double y = w/10; // set y = 4.5 • double z = x/10; // set z = 4.0 not 4.5 !!??!! • double z = ((double)x)/10; // set z = 4.5 • int q = 3 + 4 * 5; // sets q to 23, not 60 !!?!?
Arrays • Java has one built-in “primitive” data structure • When array is created, its capacity must be specified (with any integer expression!) and then can’t change System.out.println("Enter the number of cities >"); int ncities = Integer.valueOf(stdin.readLine()).intValue(); int rainfall[ncities]; String name[ncities]; for (int i = 0; i < cities.length; i++) { System.out.print("City " + i + " name > "); name[i] = stdin.readLine(); System.out.print("City " + i + " rainfall > "); rainfall[i] = Integer.valueOf(stdin.readLine()).intValue(); } (danger -- no exception handling for simplicity)
Defining methods class Rectangle { int height, width; int area() { return height*width; } void wider(int delta) { width += delta; } void taller(int delta) { height += delta; } RETURN-TYPE NAME( ARG1, ARG2, … ) { BODY } }
The Dereference (“Dot”) Operator • If X is an an object of some class C that contains an instance variable Y, then X.Y accesses that value of Y in object X • Methods work exactly the same way • stdin.readLine().toLowerCase().indexOf(“dog”) the position in that string of the first occurrence of “dog” the string formed by replacing all UPPER case letters with lower the next string entered at the keyboard the keyboard standard-input object
Sample practical problem • R1.13 - write a Java function that takes an integer n and returns the sum of the odd integers smaller than n. class R113 { static int oddsum(int x) { … return …; } } Assumption: presumably the sum of all positive ints x ! We need to loop over all odd integers less than x We need a variable to store the sum
R113 - continued int sum = 0; for (int i = 1; i<=x; i+=2) { … // i=1,3,5,… } Before proceeding… does this loop stop at the correct value of i??
R113 - continued int sum = 0; for (int i = 1; i<x; i+=2) { sum += i; } // now sum = sum of all odd integers less than x Does this handle negative values of x properly? Does this handle zero properly? Does this handle one properly? Hint: what is the minimum number of times any “for” loop will execute!
R113 - putting it all together class R113 { static int oddsum(int x) { if (x<2) return 0; // special case! int sum = 0; for (int i=1; i<x; i+=2) { sum += i; } return sum; } public static void main(String[] args) { int i = 6; // “regular” input int osi = oddsum(i); System.out.println("got " + osi + " should be 9"); int j = -10; // problem with negative inputs? int osj = oddsum(j); System.out.println("got " + osj + " should be 0"); int k = 5; // problem with odd inputs? int osk = oddsum(k); System.out.println("got " + osk + " should be 4"); } }