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
CS 303E Lecture 3 A First Java Program L & O Chapter 2 If you can't write it down in English, you can't code it. -Peter Halpern, Brooklyn, New York CS303E The First Java Program 1 Syntax and Semantics Syntax: Form or grammar. Will give syntax rules for the language. THIS PART IS FRUSTRATING!! Semantics: Meaning. What a particular element of the language causes to happen. THIS PART IS CHALLENGING!! CS303E The First Java Program 2 English is Easier than Java Git over here and tale mee where libary is at. • The meaning can still be determined if the syntax is not perfect. Not so in programming languages. Kitty get over here and fast. • The meaning of this statement? CS303E The First Java Program 3 Variables Variable A place in memory that holds a value that may be altered Declared to have a name and type: e.g., int fahrenheit; Declare variable for age and another for number of credit hours Name variables to minimize confusion about the semantics of the statement. CS303E The First Java Program 4 Declaring a Variable int numDaysLeftInSemester; What is the variable’s type? What is the variable’s name? In memory 4 bytes used for an int. ? numDaysLeftInSemester CS303E The First Java Program 5 Literals and Expressions Literal A constant: e.g., 5, 9, 3.14159 Like arithmetic expressions in algebra, except use * for multiplication, / for division, and Java variable names may be long. PMDAS: Precedence is: parentheses, inner most first multiplication and division, addition and subtraction. CS303E The First Java Program 6 Assignment Assignment Statement: Syntax: <variable> = <expression>; <variable> and <expression> are to be replaced by the name of a variable and an expression. Examples: X = X + 5; // Mathematicians leaping to their feet in protest centigrade = (fahrenheit - 32) * 5 / 9 A = A * B; A = AB; Semantics: Find the value of the expression and place the value in the variable. CS303E The First Java Program 7 More on Assignment Statements First source of problems Can’t put square peg in round hole Can’t get in the club without the right ID int myHappinessLevel; myHappinessLevel = 106; //Large assignment given ? myHappinessLevel = 0.05; 106 myHappinessLevel CS303E The First Java Program 8 More on Variable Names Variable names should be long enough to aid in the understanding of the meaning or semantics of the program, but no longer. x = y - (y * z); netPay = grossPay - (grossPay * taxRate); CS303E The First Java Program 9 Window Objects <type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>); Label degreesFahrenheitLabel = addLabel ("Degrees Fahrenheit",1,1,1,1); IntegerField degreesFahrenheitField = addIntegerField (0,1,2,1,1); Label degreesCentigradeLabel = addLabel ("Degrees Centigrade",2,1,1,1); IntegerField degreesCentigradeField = addIntegerField (0,2,2,1,1); Button convertButton = addButton ("Convert",3,1,2,1); WINDOW OBJECTS ARE SIMILAR TO VARIABLES. THEY TAKE UP SPACE IN MEMORY. CS303E The First Java Program 10 Window Object Dissected IntegerField ageField = addIntegerField (21,3,2,1,1); Initial value = Row = Column = Width = Height = CS303E The First Java Program 11 Where in the Window? IntegerField ageField = addIntegerField (21, 3, 2, 1, 1); IntegerField x = addIntegerField(0, 1, 1, 1, 1); IntegerField y = addIntegerField(12, 2, 3, 1, 1); 1 2 3 column 1 2 3 row CS303E The First Java Program 12 Methods Method calls: (What is the Window Object?) fahrenheit = degreesFahrenheitField.getNumber(); degreesCentigradeField.setNumber (centigrade); Method definition: public void buttonClicked (Button buttonObj) { fahrenheit = degreesFahrenheitField.getNumber(); centigrade = (fahrenheit - 32) * 5 / 9; degreesCentigradeField.setNumber (centigrade); } Messages: another terminology. When a method is called or invoked it sends a message to the object CS303E The First Java Program 13 Methods in Action •public class FahrenheitToCentigrade •The main program is called FahrenheitToCentigrade • When the program is run a FahrenheitToCentigrade object is created. This object contains numerous Windows objects. • How do the they communicate? •Methods and messages!! CS303E The First Java Program 14 Messages and Methods in Action FahrenheitToCentigrade Object degreesFahrenheitField.getNumber(); // sends message degreesFahrenheitField Object Code for the method resides here. (how does an IntegerField getNumber?) Object Type = IntegerField Object Name = degreesFahrenheitField CS303E The First Java Program 15 Edit, Compile, Run Steps in creating and running a program: Edit -- write the program with an editor. Compile -- translate into byte code. Run -- JVM executes the byte code. If there are errors, repeat. You will never have an error. (Gales of laughter now follow.) CS303E The First Java Program 16 The Edit, Compile, Run Visual Program Design EDIT Java Libraries MyProg.java Compile Byte Code Produced Here Java Libraries MyProg.class Program Input Program is run by a Java Virtual Machine CS303E The First Java Program RUN Program Output 17 Errors Syntax errors -- caught by the compiler. Run-time errors -- caught when the program is run. Semantic errors -- caught by the programmer. Program runs but doesn’t do what you wanted. CS303E The First Java Program 18 Syntax Error Forgetting a semicolon on int fahrenheit Sometimes not so helpful CS303E The First Java Program 19 Runtime Error Divide by zero is classic example. Change FahrenheitToCentigrade and add a variable for the divisor. CS303E The First Java Program 20 Semantic Errors The hardest to find and fix Right after pushing convert. – Not so much! CS303E The First Java Program 21 FahrenheitToCentigrade Program, text p. 15 import java.awt.*; import BreezyGUI.*; public class FahrenheitToCentigrade extends GBFrame { Label degreesFahrenheitLabel = addLabel ("Degrees Fahrenheit",1,1,1,1); IntegerField degreesFahrenheitField = addIntegerField (0,1,2,1,1); Label degreesCentigradeLabel = addLabel ("Degrees Centigrade",2,1,1,1); IntegerField degreesCentigradeField = addIntegerField (0,2,2,1,1); Button convertButton = addButton ("Convert",3,1,2,1); (continued on next slide) CS303E The First Java Program 22 FahrenheitToCentigrade Program (continued) int fahrenheit; int centigrade; public void buttonClicked (Button buttonObj) { fahrenheit = degreesFahrenheitField.getNumber(); centigrade = (fahrenheit - 32) * 5 / 9; degreesCentigradeField.setNumber (centigrade); } public static void main (String[] args) { Frame frm = new FahrenheitToCentigrade(); frm.setSize (200, 150); frm.setVisible (true); } } CS303E The First Java Program 23 Window Design [See Fig. 2.3, text p. 20.] Remember: <type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>); So far we have: • Label • IntegerField • Button Many more to come. CS303E The First Java Program 24 CS 303E Lecture 4 Java Basics 1 Chapter 3 Once a person has understood the way variables are used in programming, (s)he has understood the quintessence of programming. -Dijkstra CS303E The First Java Program 25 Case 3.1 -- Area of Circle Makes simple transformations from program FahrenheitToCentigrade. • If you can reuse your code in this class, do it! Type double numbers, DoubleField boxes. • Extraordinarily similar to what? CS303E The First Java Program 26 Request and Analysis Request • write a program that computes the area of a circle. Design • Area of circle = r2 • get radius from user • compute and display area CS303E The First Java Program 27 Area of Circle Design get radius area = 3.14 * radius * radius display area with 2 digits after the decimal point • Again, input - process - output. • concerns? CS303E The First Java Program 28 Elements of the GUI Label radiusLabel = addLabel ("Radius",1,1,1,1); DoubleField radiusField = addDoubleField (0,1,2,1,1); Label areaLabel = addLabel ("Area",2,1,1,1); DoubleField areaField = addDoubleField (0,2,2,1,1); Button computeButton = addButton ("Compute",3,1,2,1); Remember: initial value, row, column, width, height CS303E The First Java Program 29 The Guts of Button Clicked public void buttonClicked (Button buttonObj){ radius = radiusField.getNumber(); area = 3.14 * radius * radius; areaField.setNumber (area); areaField.setPrecision(2); } What is areaField.setPrecision(2); ???? CS303E The First Java Program 30 Case 3.2 -- Income Tax More simple transformations from program FahrenheitToCentigrade. Analysis a little more in depth. • flat tax rate of 20%, $10,000 standard deduction, $2,000 deduction for each dependent, • Must know something about figuring taxes to do this or must ask requestor to clarify. CS303E The First Java Program 31 Income Tax Program Type int and double variables, IntegerField and DoubleField boxes. An additionl box for input. (2 inputs) Get both inputs for computation. Yet again • input - process - output Look at program in JBuilder. CS303E The First Java Program 32 Income Tax Program Variables int grossIncome; int numberOfDependents; double taxableIncome; double incomeTax; Double is a data type. Floating point numbers: 3.14, 12.232301, 0.000001 CS303E The First Java Program 33 Income Tax Button Clicked public void buttonClicked (Button buttonObj){ grossIncome = grossIncomeField.getNumber(); numberOfDependents = numberOfDependentsField.getNumber(); taxableIncome = grossIncome - 10000 - numberOfDependents * 2000; incomeTax = taxableIncome * 0.20; incomeTaxField.setNumber (incomeTax); incomeTaxField.setPrecision (0); } Is the taxable income variable necessary? CS303E The First Java Program 34 Constants What do the numbers 10000, 2000, and 0.20 represent in the income tax program? These numbers should be declared as constants. final int STANDARD_DEDUCTION = 10000; final int DEPENDENT_DEDUCTION = 2000; final double TAX_RATE = 0.20; CS303E The First Java Program 35 Constants Constants share some similarities with variables. • they have a data type • they take up space in memory The major differences is constants cannot be changed in the program. 0.20 TAX_RATE = 12; causes syntax error TAX_RATE CS303E The First Java Program 36 Binary Represenation Bits , bytes. Integers, floating point numbers, characters, Strings and other data, and instructions All are represented in binary using bits, short for binary digit, 1s and 0s Memory -- an array of bytes. Self Test How much memory to store a picture 20 by 30 pixels, each pixel can be 1 of 256 possible colors. CS303E The First Java Program 37 Variable Names Reserved words -- can’t use these for variable names. Java already has a meaning for them. • Not that many of them. abstract boolean break byte else case extends catch char finally class float const default if private do implements double import public instanceof return int short final interface long super native switch for new continue goto CS303E throw protected throws transient try void static volatile while synchronized packagethis The First Java Program 38 Varaiable Names Continued Identifier -- a name. Composed of letters, digits, ‘_’ and ‘$’ and beginning with a letter or ‘_’. Don’t use ‘$’. Upper- and lower-case letters are considered different. “Case sensitive.” Common practice to capitalize the first letter of each word in a variable name except the first Constant names all caps with ‘_’ between words CS303E The First Java Program 39 Valid or not? just_in_time c1212 int class num my_happiness_factor TANJ x battingAverage classTime X 5bestTimes gross% total+Income totalGold _total_time TotalIncome public tax& variable 1time money$ 5 aVariableToHoldMoneySpentSoFar CS303E The First Java Program 40 Variable Names Continued "Make things as simple as possible--but no simpler.” - A. Einstein Meaningful variable names make a program easier to understand and maintain. One of the major principles of this course. incomeTax versus it totalArea versus studentNumber versus theNumberAssignedToThisStudent CS303E ta The First Java Program 41 Expressions Operator precedence -- see p. 45. Unary ‘-’ is precedence 2 (omitted). x = -3 + -4 % means modulo • • • • The remainder from integer division. Go back to second grade, 21 5 = 4 r 1 21 / 5 = 4 21 % 5 = 1 Integer vs. floating point ‘/’ • integer division truncates the result • floating point gives a floating point answer CS303E The First Java Program 42 Unary plus and minus Expression Unary minus: –3 * –4 3 * –4 3 * – –4 Unary plus: 3 * +4 CS303E Value Better 12 –12 12 (–3) * (–4) 3 * (–4) 3 * (– (–4)) 12 3 * (+4) The First Java Program 43 Increment and Decrement Operator x ++; ++ x; x – –; – – x; Equivalent x = x + 1; x = x + 1; x = x – 1; x = x – 1; Called postfix increment prefix increment postfix decrement prefix decrement Too confusing, DON’T DO IT! z = 2 * x++; z = 2 * x; x++; z = 2 * ++x; x++; z = 2 * x; Write code that is easy to understand and maintain CS303E The First Java Program 44 Extended Assignment Operators Operator sum += x; diff –= x; product *= x; quot /= x; rem %= x; Confusing: int a = 1, b = 2; a += b += 3; CS303E Equivalent sum = sum + x; diff = diff – x; product = product * x; quot = quot / x; rem = rem % x; b = 5; a = 6; The First Java Program 45 Expressions Practice Value of variables after each statement? int x; int y; int z = 12; //yes, this is allowed and encouraged! final int MAX_UNITS = 15; double a = 2.5; x = z + 2 * 5; y = 5; y = y + MAX_UNITS; z = y % 7 + x * 2; MAX_UNITS = z; x = 15 / 4 - 2; y = 15 / (4 - 2); x = a; CS303E The First Java Program 46 Data Types Revisted Numeric types: int, double, and others integers floating point byte short int long float double less inclusive more inclusive CS303E The First Java Program 47 Numeric Types (p. 124) Type Storage Range byte 1 byte –128 to 127 short 2 bytes –32,768 to 32,767 int 4 bytes –2,147,483,648 to 2,147,483,647 long 8 bytes –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 4 bytes 3.40282347x10+38 to 1.40239846x10-45 double 8 bytes CS303E 1.79769313486231570x10+308 to 4.94065645841246544x10-324 The First Java Program 48 Mixed-Mode Operations Java converts the value of a less inclusive type (like int) to a more inclusive type (like double) before performing an operation: int i = 5; double d = 3.5; System.out.println (d + i); // Displays 8.5 CS303E The First Java Program 49 CS 303E Lecture 5 Java Basics 2 Chapter 3 "In a way, staring into a computer screen is like staring into an eclipse. It's brilliant and you don't realize the damage until its too late." - Bruce Sterling CS303E The First Java Program 50 BreezyGUI Window Objects Pages 48 - 51 in Lambert and Osborne. Window objects must have: • type, name, initial value, location, extent types so far are: • Label, IntegerField, Button, DoubleField <type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>); CS303E The First Java Program 51 BreezyGUI Methods These calls require window_object.method_name: fahrenheit = degreeFahrenheitField.getNumber(); Some return a value (e.g., getNumber), some don’t (e.g. setNumber). Some require a parameter or argument (besides the window object), which goes in the parentheses. someField.setNumber (number); CS303E The First Java Program 52 BreezyGUI Methods Some methods require multiple parameters • someObject.someMethod(param1, param2, … paramn); Multiple parameters must have the right number, order, and type. • Wrong number or type leads to syntax error • Wrong order may lead to syntax or semantic error List of BreezyGUI methods on page 51. CS303E The First Java Program 53 Strings String is a type, similar to int and double. String is an object type like BreezyGUI window objects, int and double are primitives. String literals -- use double quotes: “Hi there! My name is Raoul.” -- any characters “” -- the empty string. “453” is a string, 453 is an int. CS303E The First Java Program 54 Strings String variables: String status; String with no initial value. String customer = “Bill”; String firstName, lastName; CS303E The First Java Program String given an initial value. Several objects in one declaration, like any other type. 55 String Concatenation + concatenates Strings: String firstName = “Maria”; String lastName = “Ruiz”; String name = firstName + “ ” + lastName; // name = “Maria Ruiz” \n is the newline character (one character): String name = “Jose Garcia\n”; CS303E The First Java Program 56 Number + String Converts int a = 5, b = 6; String result = a + " plus " + b + " equals " + (a + b); // result = “5 plus 6 equals 11” Conversion of a number to a String occurs with number + String or String + number. number + number still does addition. (a + b) above is needed to make this addition, not String concatenation. What happens if no parenthesis? CS303E The First Java Program 57 Message Boxes BreezyGUI provides message boxes: messageBox (“Hey there!”); Pops up a separate window called a message box containing the text provided as an argument. String line1 = “Top line.\n”; String line2 = “Bottom line.”; messageBox (line1 + line2); Message box contains 2 lines. CS303E The First Java Program 58 Message Box CS303E The First Java Program 59 Message Box Behavior Message Boxes are modal. Nothing can be done in the original window until the message box is acknowledged by closing it clicking ‘x’ in upper right corner. Too many message boxes make for a very annoying program. Use sparingly. CS303E The First Java Program 60 Text Fields TextField -- BreezyGUI window component type containing one line of String data. Declared like other window components: TextField <name> = addTextField (<initial value>, <row#>, <col#>, <width>, <height>); Methods: name.getText() -- returns String name.setText (aString) -- sets field content. CS303E The First Java Program 61 Case 3.3 - Vital Statistics import java.awt.*; import BreezyGUI.*; public class VitalStatistics extends GBFrame{ Label nameLabel = addLabel ("Name",1,1,1,1); TextField nameField = addTextField ("",1,2,1,1); Label heightLabel = addLabel ("Height",2,1,1,1); IntegerField heightField = addIntegerField (0,2,2,1,1); Label weightLabel = addLabel ("Weight",3,1,1,1); IntegerField weightField = addIntegerField (0,3,2,1,1); Button displayButton = addButton ("Display",4,1,2,1); // What will window look like? CS303E The First Java Program 62 Window Layout CS303E The First Java Program 63 String name, outputString; int height, weight; public void buttonClicked (Button buttonObj){ name = nameField.getText(); height = heightField.getNumber(); weight = weightField.getNumber(); outputString = "Name: " + name + "\n" + "Height: " + height + " inches\n" + "Weight: " + weight + " pounds\n"; messageBox (outputString); } // how many lines of text in message box? public static void main(String[] args){ Frame frm = new VitalStatistics(); frm.setSize (200, 150); frm.setVisible(true); } } CS303E The First Java Program 64 System.out.println System.out.println (expression); // with newline System.out.print (expression); // without newline Prints the value of expression to the DOS window. Expression is converted to a String if it is not one. Useful for debugging. CS303E The First Java Program 65 Debugging in JBuilder and Codewarrior System.out.println statements are very useful May also step through program • F8 Step Over • F7 Trace Into Setting Breakpoints can halt execution at a statement in the program. Contents of variables and objects may be examined CS303E The First Java Program 66 Assignment 2 Handed out today CS303E The First Java Program 67 Mixed-Mode Assignment Java converts the value of a less inclusive type to a more inclusive type before performing an assignment, but not vice versa: int i = 5; double d = 3.5; d = i; System.out.println (d); i = d; System.out.println (i); CS303E // Displays 5.0 // Syntax error The First Java Program 68