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
Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4 CompSci 001 6.1 Java programs Java programs are created as text files using a text editor (like emacs) Save to disk with .java file extension HelloWorld.java The file contains characters (stored as bytes) file can be printed, displayed on monitor, or edited file cannot be directly executed (run) by the computer system Java must first translate the program into bytecodes before it can be run CompSci 001 6.2 Bytecodes Java bytecode machine instruction for the Java processor Java compiler javac translates the source program into bytecodes Bytecode file has same name as the source program with a .class file extension: HelloWorld.class HelloWorld.java javac HelloWorld.class source program Java compiler Java bytecodes CompSci 001 6.3 Java Virtual Machine (JVM) Bytecode (class) file will contain exactly the same bytecodes no matter what computer system is used Bytecode file is executed by a Java bytecode interpreter processor specific executable program Each type of computer system has its own Java interpreter that can run on that system Any computer system can execute Java bytecode programs if it has a Java interpreter Computers with Java interpreters are called Java Virtual Machines a “computer” with a Java processor that can run Java bytecodes CompSci 001 6.4 Java applets An applet is a Java bytecode program that runs on a Web browser Most newer Web browsers have Java interpreters Web pages on the Internet contain instructions that send Java bytecodes to your computer Web browser runs the Java applet with its built-in interpreter CompSci 001 6.5 Data types Computer memory stores arbitrary bit patterns Meaning of a bit pattern depends on its use Pattern used for a particular string of bits is a data type values are any kind of data a computer can process all values are represented using some data type Example: What does the following pattern of 16 bits represent? 0000000001100111 No way to know without more information If data type is short (a Java type) it represents 103 CompSci 001 6.6 Java data types Primitive types of data that are so fundamental ways to represent them are built into Java Object built-in or user-defined CompSci 001 6.7 Primitive data types All primitive values belong to one of eight primitive types byte short double int long float char boolean Primitive data types use a fixed number of bytes four of these types designate different sizes of bounded integers: byte, short, int, long A programmer can not create new primitive data types Any data type you invent will be a type of object Most commonly used types in practice: int, boolean, and double CompSci 001 6.8 Java primitive data types Primitive Type Description Range byte 8-bit integer -128 to 127 short 16-bit integer -32768 to 32767 int 32-bit integer -2147483648 to 2147483647 long 64-bit integer -263 to 263-1 float 32-bit floating point 10-46 to 1038 double 64-bit floating point 10-324 to 10308 char Unicode character boolean Boolean variable CompSci 001 false and true 6.9 Basic operators Operator Assignment Arithmetic Unary Equality Relational Logical CompSci 001 Java = +,-,*,/,% -,++,-==, != <,<=,>,>= &&,||,! Description assigns rhs to lhs addition, subtraction, multiplication, division, remainder negative, auto increment, auto decrement equals to, not equals to less than, less than or equals to, greater than, greater than or equals to AND, OR, NOT 6.10 Variable declaration Declaration type <variable-name>; Declaration + initialization: type <variable-name> = <value>; Variable names any combination of letters, numbers, and the underscore character may not start with number may not be reserved word • e.g. int, return, if, for, while may not be same as a subroutine name case-sensitive (num and Num are different) CompSci 001 6.11 Examples int x, y, z; int sum = 0; float f; double pi = 3.14; char first = ‘T’, middle = ‘L’, last = ‘B’; char first = ‘T’; char middle = ‘L’; char last = ‘B’; CompSci 001 6.12 Operator precedence Evaluate a + b * c multiplication first? a + (b * c) addition first? (a + b) * c Java solves this problem by assigning priorities to operators (operator precedence) operators with high priority are evaluated before operators with low priority operators with equal priority are evaluated left to right Operator priority (highest to lowest) 1. 2. 3. 4. CompSci 001 ( ) * / + = % 6.13 When in doubt, use parentheses a + b * c = a + (b * c) because * has higher priority than + To perform the + operation first we need to use parentheses (a + b) * c If in any doubt use extra parentheses to ensure the correct order of evaluation parentheses are free! cause no extra work for the computer only make it easier for you to work out what is happening CompSci 001 6.14 Examples Java adheres to traditional order of operations * and / have higher priority than + and – int x = 3 + 5 * 6; (x = 33) int y = (3 + 5) * 6; (y = 48) Parentheses are free, use them liberally int z = ((3 + 5) * (6)); (z = 48) Equal priority operations are evaluated left-to-right in the absence of parentheses int w = 3 * 4 / 2 * 6; (w = 36) int x = 3 * 4 / (2 * 6); (x = 1) int y = 3 * 4 + 2 * 6; (y = 24) int z = 3 * (4 + 2) * 6; (z = 108) CompSci 001 6.15 Syntax and semantics Addition, subtraction: + and –, int and double int x = 21+4; (x = 25) double y = 14.1-2; (y = 12.1) Multiplication: *, int and double int x = 21*4; (x = 84) double y = 14.1*2.5; (y = 35.25) Division: /, different for int and double int x = 21/4; (x = 5) double y = 21/4; (y = 5.0) double y = 21/4.0; (y = 5.25) Modulus: %, only for int int x = 21%4; (x = 1) CompSci 001 6.16 Automatic type conversion Mixed type expressions are converted to higher compatible types If all operands are of type int then result is type int If any operand is of type double then result is of type double Cannot convert to a lower type Conversion may result in loss of precision CompSci 001 Example: Convert Fahrenheit to Celsius double F=41.0; double C=(F-32.0)*(5/9); Question: What is the value of C? a) 5 b) 0.0 c) 9.0 d) 5.0 e) 9 6.17 More expressions int g = 12 + 2.5; What is the value of g? a. 0 b. 12 c. 14 d. 14.5 e. int n = 1 – 2 * 3 – (4 + 5); What is the value of n? error int x = 8 * (7 – 6 + 5) % (4 + 3 / 2) – 1; What is the value of x? a. -1 b. 0 c. 2 d. 3 e. none of the above CompSci 001 6.18 Syntax errors The following Java subroutine computes the inclusive sum between two integers. Find all the syntax errors. CompSci 001 int sumBetween( x, y ) { int z = x; Int sum = 1; while( z <= y ){ sum = sum*z; z++ } } 6.19 Logic errors The computer will do precisely what you say even though it may not be what you want What is wrong with this code? int sumBetween( int x, int y ) { int z = x; int sum = 1; while( z <= y ) sum = sum*z; z++; } CompSci 001 6.20 Java objects Java is an object-oriented programming language use objects to define both the data type and the operations that can be applied to the data Objects have attributes and functionality attributes describe the state of the object the functionality of an object is the set of actions the object can perform In Java, we define an object’s attributes using variables and its functionality using methods CompSci 001 6.21 Real-world objects Suppose we want to describe a car in terms of its attributes and functionality Attributes: int year; int mileage; String make; String model; boolean manual_transmission; Methods: void brake() int getMileage() boolean needsGas() void shift(int gear) CompSci 001 6.22 Java classes Java objects are created using classes Encapsulation combining elements to create a new entity A class encapsulates the variables and methods that define an object Instantiation the act of creating an object objects are called class instances Java provides many predefined classes You can also define your own classes CompSci 001 6.23 Java String class The String class represents character strings String first = “Tammy”; String last = “Bailey”; Strings can be concatenated (added together) using the concatenation operator + String fullname = first + “ ” + last; Testing for equality: first.equals(“Tammy”); /* returns true */ first.equals(“Amy”); /* returns false */ CompSci 001 6.24 Instantiation Creating an object is called instantiation the new operator is used with class name Example: Create a TextField object TextField t = new TextField(); Can create multiple instances of the same class TextField t1 = new TextField(); TextField t2 = new TextField(); Exception the new operator is not required when creating a String CompSci 001 6.25 Java TextField class The TextField class allows the editing and display of a single line of text TextField t = new TextField(); Methods setText(String s) • set the text of the field to the string s String getText() • get the text of the field and assign it to a variable of type string CompSci 001 6.26 Invoking an object’s methods Once we create a text field, we can perform actions on it using its methods The variables and methods of an object are accessed using the dot operator TextField t = new TextField(); t.setText(“Hello”); Syntax object.verb(data); Perform verb on object using data CompSci 001 6.27 Interactive objects User interaction determines the behavior of the program Program receives user input through mouse and keyboard and performs associated method or action Text fields edit and display single line of text Buttons can specify action to occur when button is clicked CompSci 001 6.28 Action listeners If we want a button to know when it is clicked, we have to enable it to “listen” for user input Use the button method addActionListener Button b = new Button(“click!”); b.addActionListener(this); If we don’t invoke the addActionListener method on a button, nothing will happen when the button is clicked CompSci 001 6.29 Example We would like our applet to do the following: get text from text field t1 and display it in text field t2 when button b is clicked TextField t1 = new TextField(); TextField t2 = new TextField(); Button b = new Button(“copy text”); b.addActionListener(this); CompSci 001 6.30 Numeric input Suppose we want an applet that allows the user to enter two integers and display the minimum a text field contains a character string If we want to perform numeric operations on the input from a text field, we have to convert the string to a numeric data type numbers are primitive data types, not objects Can convert using Java type wrappers CompSci 001 6.31 Decision trees If-Then statements if (logical expression) { “true” actions } If-Then-Else statements if (logical expression) { “true” actions } else (logical expression 2) { “false” actions } CompSci 001 Logical expressions analogous to yes or no questions true or false Statements that are true (5 < 7) (100 == 100) (100 != 10) (10 <= 10) Statements that are false (-2 > -1) (10 != 10) 6.32 A decision tree 3 1 Would you like to read about Einstein? He received the Physics Price in 1921. 4 Try the Medicine Prize in 1962. 0 Would you like to read about a scientist? 5 Would you prefer a humanitarian? CompSci 001 2 Look up the Peace Prize in 1991. 6 Try A. Solzhenitsyn, Literature 1970. 6.33 More Java Syntax Assignment statement variable = expression; Method invocation Also called function or procedure Invoking also called “calling” a function Methods can take arguments button.setText(“This text is an argument”); init() Variable declaration VariableType variableName; Button choice; CompSci 001 6.34 Java Details Java tutorial http://java.sun.com/docs/books/tutorial 1. Do “Your First Cup of Java” and create your First Applet 2. Go to “Learning the Java Language” and read “Language Basics” Variable: an item of data named by an identifier Operators Arithmetic Relational and conditional Assignment Other Expression: a series of variables, operators, and method calls that evaluates to a single value CompSci 001 6.35 Dealing with numbers Primitive data type: int Does not require a new statement to create Primitive types not classes Must declare Should initialize (Java sets to 0) Other primitive types include: boolean, char, double Operations using integers +, -, *, /, % Operator Precedence CompSci 001 6.36 Some arithmetic details Java adheres to traditional order of operations * and / have higher precedence than + and – int x = 3 + 5 * 6; Parentheses are free, use them liberally Arithmetic expressions are evaluated left-to-right in the absence of parentheses int x = 3 * 4 / 6 * 2; int y = (3 + 5) * 6; int y = (3*4)/(6*2); There are limits on int and double value, be aware of them. CompSci 001 6.37 Types for Numbers The type String is not a built-in type, technically it’s a class There are many numerical types in Java We’ll use two int, represents integers: {…-3,-2,-1,0,1,2,3,…} • Conceptually there are an infinite number of integers, but the range is limited to [-231, 231-1] or [Integer.MIN_VALUE,Integer.MAX_VALUE] • Alternatives? Why is range limited? double, represents real numbers like , 2 • Not represented exactly, so expressions like 100*0.1 may yield unexpected results • Double precision floating point numbers, another type float exists, but it’s a terrible choice (generates poor results) CompSci 001 6.38 GIGO: program as good as its data? In calculations involving floating point numbers it’s easy to generate errors because of accumulated approximations: What is 1023 + 1? When is (x + y) + z different from x + (y + z) ? The type int is severely constrained on 16-bit computers, e.g., running DOS, largest value is 32,767 (215-1) Even on 32-bit machines, how many seconds in a millennium? 60*60*24*365*1000, problems? On UNIX machines time is measure in seconds since 1970, problems? What was Y2K all about? CompSci 001 6.39 What arithmetic operations exist? Syntax and semantics for arithmetic operations Addition, subtraction: + and –, int and double 23 + 4 d * 23.1 * 4 21 / 4.0 x / y Modulus: %, only for int 21 % 4 y * 3.0 Division: /, different for int and double 21 / 4 d – 14.0 + 23 Multiplication: *, int and double 23 * 4 x + y 17 % 2 x % y Mixed type expressions are converted to “higher” type Associativity of operators determines left-to-right behavior Use parentheses liberally Without () use operator precedence, *,/, % before +,- CompSci 001 6.40 Dealing with text Strings are a class and not a primitive datatype Declaration: String message; String Constants “Good Morning World!” String Assignment message = "It's Friday"; CompSci 001 6.41 Manipulating Strings Methods for manipulation int length() int indexOf(String st) String substring(int start, int end) Getting String Data from user The TextField class has getText() method Use: message = mg.getText(); • where mg is a TextField and message is a String CompSci 001 6.42 Evaluating expressions Order of precedence Operators Associativity Type () * + < == = / % <= > != left to right left to right left to right >= left to right left to right right to left Parentheses Multiplicative Additive Relationals Equalities Assignment Automatic type conversion Values of one type are promoted to another compatible type as part of the computation process CompSci 001 You can convert Tf degrees Fahrenheit to Tc degrees Celsius using the formula: Tc = (5/9)*(Tf-32) Given the following expression: double Tc = (Tf – 40.0) * (5/9) If Tf is –40.0 what is Tc? 1. -40.0 2. 0.0 3. 40.0 4. error 5. unknown 6.43 More expressions int n = 1 - 2 * 3 - 4 + 5; What is n? 1. 2. 3. 4. 5. 6. -4 -2 0 2 4 error int n = 12 + “hello” 1. 2. 3. 4. 5. 0 12 17 unknown errror CompSci 001 int x = 8 * (7 – 6 + 5) % (54 + 3 / 2) – 1; What is x? 1. -1 2. 0 3. 2 4. 3 5. error 6. something else 6.44 Repeating code Repeating code is bad Writing repetitive code is tedious Debugging repetitive code is hard Avoid repeating code through: Subroutines/methods Loops CompSci 001 6.45 Loops If statements need to repeat, then you probably need a loop Describe portion of program as: Repeat Continue until For each value from 1 to n For every object of a set, do something We have already used iteration by using the buttons How? CompSci 001 6.46 Problems We want to: Print out all numbers from 0up to 100 incrementing by 0.5 each time Sum up the numbers from 1 to 100 … New Java syntax New object type TextArea which is basically a big scrolling textbox tArea is 80 character wide and 20 rows high text box with 20 rows TextArea tArea = new TextArea(20,80); Add characters to the end of the TextArea using append tArea.append(“Hello\n”); ‘\n’ is called a newline character which moves the next character to the next line CompSci 001 6.47 Anatomy of a while loop While loops are one way to get rid of repetitive code Print out numbers up to 100 by increments of 0.5 x 0 true x < 100 x x + 0.5 print x x = 0.0; while (x < 100) { x = x + 0.5; tArea.append(“x = “ + x); tArea.append(“\n”); } false CompSci 001 6.48 Another loop Summing the numbers 1 … 100 int sum = 0; int k = 0; while (k < 100) { k = k + 1; sum = sum + 1; } Other Loop designs Count down Stopping and starting at computed values Data dependent loop CompSci 001 6.49 Functions/Methods Function example: distance from point (x,y) to origin Function declaration Name of the function Type of each argument to the function with a descriptive name for each argument The type of value a function returns CompSci 001 6.50 Function calling mechanics 1. 2. 3. 4. 5. The value of each argument are computed The value of each argument is copied into the corresponding formal parameter The statements in the function body are evaluated until a return statement appears The value of the return expression is evaluated The calling program continues, with the returned value substituted in place of the call CompSci 001 6.51 Functions can return strings String WeekDay(int day) { if (0 == day) { return "Sunday"; } else if (1 == day) { return "Monday"; } else if (2 == day) { return "Tuesday"; } else if (3 == day) { return "Wednesday"; } … } Shorter (code) alternatives? Is shorter better? CompSci 001 What function call looks like? String dayName; int dayNum = 4; dayName = WeekDay(dayNum); Which is/are ok? Why? result.setText(WeekDay(5)); int j = WeekDay(0); result.setText(WeekDay(2.1)); String s = WeekDay(22); WeekDay(3); 6.52 Think about it Puzzle: Toggling Frogs You have 100 light switches, numbered 1-100, and 100 frogs, also numbered 1-100. Whenever a frog jumps on a light switch, it toggles a light between on and off. All lights are initially off. • frog #1 jumps on every light switch (ie turning them all on). • frog #2 jumps on every 2nd light switch, toggling some of them back off. ... • frog #k jumps on every kth light switch. After 100 frogs, which lights are on? Game: Don’t be last You and a friend have a stack of 10 coins. On each person's turn, they remove either 1 or 2 coins from the stack. The person who removes the last coin wins. What is a winning strategy? Should you go first or second? CompSci 001 6.53 Arrays Aggregate data type Deal with items of same type Lists numbers words … Analogies Mailboxes in post office CD racks with slots Simplifies naming Allows use of loops Required for many mathematical and statistical problems Multiple elements or cells CompSci 001 6.54 Using arrays subscript or index to access element x[5] = 20; foo.setText(“Result is " + x[5]); Often used in loops int k while { k = sum } CompSci 001 = 0; sum = 0; ( k < 10 ) k + 1; = sum + name[k]; 6.55 Creating Arrays Declaration double weights[]; Definition weights = new double[50]; Combine double weights[] = new double[50]; int num[] = new int[6]; ? ? = 13; ? num[1] =? 21; ?num[5] ? CompSci 001 21 ? ? ? ? 13 6.56 Arrays & Loops int k = 2; while(k<6) { num[k] = k*k; k = k+1; } ? CompSci 001 21 4 9 16 25 6.57