Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CMPSCI 187 Introduction to Programming with Data Structures Computer Science 187 Lecture 2 Java Overview Announcements: Be sure to try your EdLab accounts. Make sure you can transfer a text file from your machine to your EdLab account Discussion sections will meet tomorrow First programming assignment will be up next week 1 CMPSCI 187 Java is a modern object oriented programming language. Our main objective will be to write Java classes. Java distinguishes two kinds of entities A Quick Overview of Java: BASICS Primitive types Objects Look at these first An object is a specific instance of a class. The type of an object is the same as the name of the class from which it was created. Classes contain 2 different kinds of members: descriptions of data (fields) and algorithms for manipulating the data (methods). Writing Java programs involves writing class templates. The useful links page contains pointers to on-line Java tutorials. 2 CMPSCI 187 Primitive Data Types Represent numbers, characters, boolean values Integers: byte, short, int, and long Real numbers: float and double Characters: char Boolean values: true and false 3 CMPSCI 187 Primitive Data Types Data type Range of values byte -128 .. 127 (8 bits) short -32,768 .. 32,767 (16 bits) int -2,147,483,648 .. 2,147,483,647 (32 bits) long -9,223,372,036,854,775,808 .. ... (64 bits) float +/-10-38 to +/-10+38 and 0, about 6 digits precision double +/-10-308 to +/-10+308 and 0, about 15 digits precision char Unicode characters (generally 16 bits per char) boolean True or false 4 CMPSCI 187 Primitive Data Types (continued) 5 CMPSCI 187 Operators 1. 2. 3. 4. 5. 6. 7. 8. 9. subscript [ ], call ( ), member access . pre/post-increment ++ --, boolean complement !, bitwise complement ~, unary + -, type cast (type), object creation new * / % binary + - (+ also concatenates strings) signed shift << >>, unsigned shift >>> comparison < <= > >=, class test instanceof equality comparison == != bitwise and & bitwise or | 6 CMPSCI 187 Operators logical (sequential) and && 12. logical (sequential) or || 13. conditional cond ? true-expr : false-expr 14. assignment =, compound assignment += = *= /= <<= >>= >>>= &= |= 11. 7 CMPSCI 187 Type Compatibility and Conversion Widening conversion: In operations on mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range In an assignment, a numeric type of smaller range can be assigned to a numeric type of larger range byte to short to int to long int to float to double 8 CMPSCI 187 Naming Variables A program refers to a variable's value by its name. For example, when a Hello method wants to refer to the value of the who variable, it simply uses the name who. In Java, the following must hold true for a variable name 1. It must be a legal Java identifier comprised of a series of Unicode characters. Unicode is a character-coding system designed to support text written in diverse human languages. It allows the codification of up to 65,536 characters, currently 34,168 have been assigned. This allows you to use characters in your Java programs from various alphabets, such as Japanese, Greek, Cyrillic, and Hebrew. This is important so that programmers can write code that is meaningful in their native languages. 2. It must not be a keyword or a boolean literal (true or false). 3. It must not have the same name as another variable whose declaration appears in the same scope. 9 CMPSCI 187 Declaring and Setting Variables int square; int n = 10; square = n * n; double cube = n * (double)square; Can generally declare local variables where they are initialized All variables get a safe initial value anyway (zero/null) 10 CMPSCI 187 Referencing and Creating Objects You can declare reference variables They reference objects of specified types Two reference variables can reference the same object The new operator creates an instance of a class A constructor executes when a new object is created Example: String greeting = “hello”; 11 CMPSCI 187 Naming Conventions By Convention: Variable names begin with a lowercase letter. Class names begin with an uppercase letter. If a variable name consists of more than one word, such as isVisible, the words are joined together and each word after the first begins with an uppercase letter. 12 CMPSCI 187 Things to Remember { } delimit logical blocks of statements /* up to */ defines a comment (ignored by Java) // defines a single line comment Java is case-sensitive: out, Out, OUt, OUT etc. are different Primitive Types: integers, floating point numbers, booleans, and characters. NAME boolean char int long float double TYPE boolean characters integer long integer real double real RANGE true or false any character -2^31 (2^31)-1 -2^63 (2^63)-1 -3.4E38 3.4E38 -1.7E308 -1.7E308 DEFAULT false null 0 0 0.0 0.0 13 CMPSCI 187 Java Control Statements A group of statements executed in order as written { stmt1; stmt2; ...; stmtN; } The statements execute in the order 1, 2, ..., N Control statements alter this sequential flow of execution 14 CMPSCI 187 Java Control Statements (continued) 15 CMPSCI 187 Java Control Statements (continued) 16 CMPSCI 187 Control and Repetition For While If-Then-Else While Do-While Switch if (testCondition) { statement1; statement2; } else { statement3; statement4; } 17 CMPSCI 187 for Loop Repetition a fixed number of times Clearly defined condition for loop termination for (‘initialization’; ‘test’; ‘modification’) statement done once prior to beginning loop initializes the loop variable. done at beginning of each loop iteration determine whether or not this repetition has to be done. performed at the end of each iteration - sets new value for loop variable. for (int i=0; i<n; i++) statement 18 CMPSCI 187 Infinite Loops •• • int n = 1; while (n != 10) { System.out.println(n ); n = n+2; } •• • •• • int n = 1; do { System.out.println(n); n = n+2; } while (n!=10); •• • Note: n is never equal to 10, which is the condition for loop termination! 19 CMPSCI 187 Classes and Objects: First Look Class : a blueprint for an object Objects : defined by and created from classes (blueprints) House Blueprint Houses from same Blueprint (generic) new house158(asphalt, clapboards) new house158(asphalt, stucco) house158 Figure adapted from Lewis and Loftus: Java Software Solutions, p.123 new house158(tile, stucco) 20 CMPSCI 187 Object Oriented Programming In classic procedural programming procedures and functions are active; data elements are passive. In object-oriented programming data elements - objects - are fundamental and central. methods (e.g. like procedures and functions) serve the objects. A class is a programmer-defined type that serves as a blueprint for instances (objects) of the class. 21 CMPSCI 187 Extensibility Java supports primitive types: ints, floats, Strings, arrays, etc. ; Primitive types are used to construct new types: cars, motorcycles, people, buildings, clouds, dogs, angles, students, courses, bank accounts, ….and any other type that's important to your problem. These can, in turn, be used to construct other types 22 CMPSCI 187 Structure of a Class Definition Class name with class modifiers Class fields: the data associated with the class (typed with field modifiers) Class constructors: how to build an instance of the class typically how to initialize the instance's data fields Class methods: how to manipulate the data to get results can be thought of as procedures or subroutines in conventional languages can also have visibility attributes Let’s do an example ….. but first…. 23 CMPSCI 187 Classes and Objects Classes specify the data and behavior possessed both by themselves and by the objects built from them. Using the blueprint provided by a class, you can create any number of objects, each of which is called an instance of the class. Different objects of the same class have the same fields and methods, but the values of the fields will in general differ. Objects have the same methods as all other objects in the class except in so far as the methods depend on the value of the fields and arguments to the method. 24 CMPSCI 187 Things to Come Later we’ll look various relationships among classes, and the implications of these relationships for programming abstract classes inheritance (is-a relationships) overriding and overloading polymorphism composition (has-a relationships) interfaces a bit on file handling (for text, not binary files) 25 CMPSCI 187 Literature Comparison Once upon a midnight dreary, while I pondered weak and weary, Over many a quaint and curious volume of forgotten lore, While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. `'Tis some visitor,' I muttered, `tapping at my chamber door Only this, and nothing more.' ………..Edgar Allan Poe "The Raven" http://www.heise.de/ix/raven/Literature/Lore/TheRaven.html 'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe. "Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!" ………..Lewis Carroll ”Jabberwocky" 26 CMPSCI 187 An Example: Collecting Word Frequencies Text file containing lines of words (Given). How many times do each of the words appear in the text? List of words and their count Issues: What’s a word? R2D2? Help-session? 123.78? Other possibilities: report the words in (alphabetical) sorted order; report the words in frequency order, etc. A useful program because we’ll (very soon) recast it in many ways so that we can use the basic mechanisms to store the data -- words, along with their multiplicities -- in different data structures. http://www.georgetown.edu/faculty/ballc/webtools/web_freqs_help.html As an authoring tool: www.tinaja.com/glib/wordfreq.pdf 27 CMPSCI 187 Word Frequencies Word Freq. Text File Word Freq. Words Word Freq. WordInfo Instance WordInfo Instance WordInfo Instance RecorderV Classes: WordInfo - information about a word Words - gets words out of the file (abstract class) Recorder V - maintains the table or list of words (actually, WordInfo instances) WordtestV - test program (contains the main method) 28 CMPSCI 187 Vectors vectors generalize arrays: they allow random access, they “grow” more or less automatically a “legacy” class in Java vectors look like arrays (and indeed are so implemented) vector elements are stored as (referenced as) Objects Basic functionality: size capacity insertElementAt(obj, j) addElement(obj) elementAt(j) removeElementAt(j) 29 CMPSCI 187 Example of Program Execution -------------------------input file -----------------now is the time Time time time time time! for all those good men; and I mean all of them, good good men to go forward. -----------------------------output -----------------now num of occurences 1 is num of occurences 1 the num of occurences 1 time num of occurences 6 for num of occurences 1 ….. them num of occurences 1 to num of occurences 1 go num of occurences 1 Forward num of occurences 1 30 CMPSCI 187 The Test Program import java.io.*; public class WordtestV { public static void main(String[] args) { System.out.println("here comes answer"); try{ String fileName = args[0]; RecorderV textfile = new RecorderV(fileName); textfile.getLines(); // all the action is here.. System.out.println("words with multiplicities: "); textfile.showScoreboard(); } catch(IOException e) {System.out.println(e);} }//end main }//end WordTestV 31 CMPSCI 187 WordInfo Class public class Wdinfo implements Comparable { private String word; private int count = 0; public Wdinfo(String s){word = s; count = public public public public public Abstract Class 1;} void setWord(String s){ word = s;} String getWord() { return word;} int getCount() {return count;} void setCount(int k) {count = k;} void incrCount(){count++;} public int compareTo(Object wd) { String s1 = this.word; String s2 = ((Wdinfo)wd).word; return s1.compareTo(s2); } public String toString() { " + count);} } return (word + Cast " count 32 CMPSCI 187 Words Class import java.io.*; import java.util.*; public abstract class Words { String fname; BufferedReader inDat; Abstract Class public Words(String dataFile) throws IOException { fname = dataFile; File inData = new File(fname); inDat = new BufferedReader(new FileReader(inData));} public void getLines() throws IOException { String line = inDat.readLine(); while(line != null) { processLine(line); line = inDat.readLine();} closeFile();} Abstract Method public abstract void processLine(String line); public void closeFile() throws IOException {inDat.close();} } 33 CMPSCI 187 RecorderV import java.io.*; import java.util.*; public class RecorderV extends Words { public Vector vocab = new Vector(100); public int last = 0; //pre: dataFile is the name of a text file to be read in //post: constructs a RecorderV object, that will hold words/cts in vector public RecorderV (String dataFile) throws IOException { super( dataFile);} 34 CMPSCI 187 The Abstract Method: processLine public void processLine(String line) //pre: line is a line of text from data file //post: breaks line into tokens, processes tokens one at a time { StringTokenizer oneLine = new StringTokenizer(line," .,;:\n\t\r"); while (oneLine.hasMoreTokens()) { String w = oneLine.nextToken(); processWord(w);} } 35 CMPSCI 187 More Methods public void processWord(String wd) //pre: wd is a string //post: if wd is indeed all letters, than wd gets installed in vec vocab { String w = wd.toLowerCase(); if (allLetters(w)) install(w); }//end processWord public boolean allLetters(String w) //pre: w is a string //post: returns true if w is all letters, else returns false { boolean ok = true; for (int j=0; ((j < w.length()) && ok); j++) if ((w.charAt(j) < 'a') || (w.charAt(j) > 'z')) ok = false; return ok; }//end allLetters 36 CMPSCI 187 Install Method public void install(String w) //pre: w is a string of pure lowercase letters //post: if already present, w's ct incremented; else w added to end of vocab { Wdinfo cur; boolean placed = false; for (int j = 0; j < vocab.size(); j++) { cur = (Wdinfo)vocab.elementAt(j); if (cur.getWord().equals(w)) {((WordInfo)vocab.elementAt(j)).incrCount(); placed = true;} } // end for if (!placed) vocab.addElement(new Wdinfo(w)); }//end install 37 CMPSCI 187 Method to Print Data public void showScoreboard() //post: the "scoreBoard" vocab is displayed { for (int j = 0; j < vocab.size(); j++) {System.out.print(((Wdinfo)vocab.elementAt(j)).getWord()+"\t"); System.out.println(" num of occurences ” +((Wdinfo)vocab.elementAt(j)).getCount());} }//end Scoreboard } //end RecorderV 38 CMPSCI 187 Main Points Summarized Vectors Abstract classes, inheritance The role of casting (but…generics -later) Comparable interface (WordInfo) Documentation pre/ post scheme is fine; JavaDoc also (as described in text) 39