Download presentation
Presentation is loading. Please wait.
Published byEarl Crawford Modified over 8 years ago
1
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Program Elements and Syntax rules COMP 102 2016T1 #4
2
© Peter Andreae COMP 102 4: 2 Menu More details about the Java Program Semantics (meaning) and Syntax (grammar rules) Methods Statements Variables, Types, Assignment, Values and Expressions Reading: L-D-C: Chapter 2 Announcements Labs: how many need to sign up yet? Class Rep.
3
© Peter Andreae COMP 102 4: 3 Class Representative Candidate…
4
© Peter Andreae COMP 102 4: 4 TemperatureCalculator import ecs100.*; /** Program for converting between temperature scales */ public class TemperatureCalculator{ /** Constructor: Set up interface */ public TemperatureCalculator (){ UI.initialise(); UI.addButton("F->C", this :: fahrenheitToCelsius); UI.addButton("Formula", this :: printFormula); } /** Convert from fahrenheit to celsius */ public void fahrenheitToCelsius(){ double fahren = UI.askDouble("Farenheit:"); double celsius = (fahren - 32) * 5 / 9; UI.println(fahren + “F is " + celsius + " C"); } /** Print conversion formula */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); }
5
© Peter Andreae COMP 102 4: 5 Structure of the program Import statements Comment Class definition (defining the objects) Class header Constructor definition (defining what to do when making a new object) Method definitions (defining Actions the objects can do) Method header Instructions for performing the action Telling an object to perform some action Putting a value into a place
6
© Peter Andreae COMP 102 4: 6 Elements of the program Comments vs Code Keywords vs Identifiers vs Strings vs numbers vs operators and punctuation Keywords : words with special meaning in the Java Language eg: public, class, if, while, … mostly to do with the structure of the program Identifiers : other words, used to refer to things in the program. mostly made up by the programmer, some are predefined. Strings : bits of text that the program will manipulate. always surrounded by " and " numbers operators and punctuation : + - * / =. ;, ( ) { } [ ] ' " all have precise meanings and rules for use
7
© Peter Andreae COMP 102 4: 7 Writing your own programs How? Use other programs as models, and guess how to modify Very useful strategy Limiting Hard to work out what's wrong if you don’t understand it
8
© Peter Andreae COMP 102 4: 8 A new program Calculator to convert inches to centimeters import ecs100.*; /** Program to convert inches to centimeters */ public class TemperatureCalculator{ ….. /** Convert from fahrenheit to celsius */ public void fahrenheitToCelsius(){ double fahren = UI.askDouble("Farenheit:"); double celsius = (fahren - 32) * 5 / 9; UI.println(fahren + “F is " + celsius + " C"); }
9
© Peter Andreae COMP 102 4: 9 Writing your own programs How? Use other programs as models, and guess how to modify Very useful strategy Limiting Hard to work out what's wrong if you don’t understand it Understand the language ⇒ vocabulary ⇒ syntax rules ⇒ meaning (“semantics”) Unlimited Able to understand and reason about your program
10
© Peter Andreae COMP 102 4: 10 Syntax rules: Program structure First version 〈import statements 〉 public class 〈 constructor description 〉 { } 〈 classname 〉 Comments can be added anywhere import ecs100.*; import java.awt.Color; 〈 method description 〉
11
© Peter Andreae COMP 102 4: 11 Comments Three kinds of comments: Documentation comments eg /** Program for converting between temperature scales */ end-of-line comments eg double Celsius = (fahren – 32) * 5 / 9; // compute answer anywhere comments eg /* double fahren = celsius * 9 / 5 + 32; UI.println(celsius + “C is " + fahren + " F"); */ /** 〈 text of comment 〉 */ // 〈 text of comment 〉 Top of class, Before each method at end of any line /* 〈 text of comment 〉 */ multi-line, or middle of line, or …
12
© Peter Andreae COMP 102 4: 12 Constructor Definitions /** Constructor: Set up interface */ public TemperatureCalculator (){ UI.initialise(); UI.addButton("F->C", this :: fahrenheitToCelsius); UI.addButton("Formula", this :: printFormula); } 〈 Doc Comment 〉〈 Header 〉〈 Body 〉 {} public () 〈 class-name 〉 instructions to perform when creating a new object
13
© Peter Andreae COMP 102 4: 13 Method Definitions /** Print out the conversion formulas */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); } 〈 Doc Comment 〉〈 Header 〉〈 Body 〉 {} public void () 〈 name 〉 〈 parameters 〉 instructions to perform this action Specifying the information the action needs. May be empty
14
© Peter Andreae COMP 102 4: 14 “Statements” (instructions) (Single instructions are called “statements” for silly historical reasons!) Two important kinds of statements: method call statement: tell some object to perform one of its methods. eg: tell the UI object to ask the user for a number eg: tell the UI object to print out a string eg: tell the UI object to add a button assignment statement compute some value and put it in a place in memory.
15
© Peter Andreae COMP 102 4: 15 Method Calls /** Print out the conversion formulas */ public void printFormula(){ UI.println( "Celsius = (Fahrenheit - 32) *5/9" ); } Method call Statement: who. what ( data to use) ; UI. println ( “Celsius = (Fahren…”) ; Meaning of Statement: Tell the object to perform the method using the argument values provided 〈 object 〉 〈 methodname 〉〈 arguments 〉.();
16
© Peter Andreae COMP 102 4: 16 Objects and their methods in Java What objects are there? Predefined eg: UIa "User Interface" window with several panes initialize(), quit(), addButton(…) println(….), drawRect(…), clearGraphics(), askDouble(…) Systemrepresenting the computer system currentTimeMillis( ) Mathmethods for mathematical calculations random( ), sin(…) Others The object(s) defined by your program New objects that your program creates Some method calls return a value
17
© Peter Andreae COMP 102 4: 17 Values / Data There are lots of different kinds of values: Numbers Integers( int or long) 42 -194573203 real numbers( double or float ) 16.43 6.626e-34 … Characters ( char )'X' '4' Text ( String ) " F -> " Colours ( Color )Color.red Color.green Method namesthis::fahrenheitToCelsius Other Objects …
18
© Peter Andreae COMP 102 4: 18 Variables /** Print out the conversion formulas (version 2) */ public void printFormula () { String formula; formula = "Celsius = (Fahrenheit - 32) *5/9" ; UI.println( formula ); } A variable is a place that can hold a value. Must specify the type of value that can be put in the variable ⇒ “Declare” the variable. Must put a value into a variable before you can use it ⇒ “assign” to the variable Can use the value by specifying the variable’s name Can change the value in a variable (unlike mathematical variable) " Use a variable whenever you need the computer to remember something temporarily.
19
© Peter Andreae COMP 102 4: 19 Assignment Statements /** Print out the conversion formulas (version 2) */ public void printFormula () { String formula; formula = "Celsius = (Fahrenheit - 32) *5/9" ; UI.println( formula ); } Assignment Statement: where = what ; name-of-place= specification-of-value ; formula= " Celsius = (Fahrenheit - 32) *5/9" Compute the value and put it in the place 〈 variable 〉〈 expression 〉 =; "
20
© Peter Andreae COMP 102 4: 20 Declarations and Assignments Variable must be declared before you use it Must be declared only once in a method Must be assigned a value before it is used in an expression Can declare variable before first assignment or Declare variable in the first assignment statement: /** Print out the conversion formulas (version 2) */ public void printFormula () { String formula = "Celsius = (Fahrenheit - 32) *5/9" ; UI.println( formula ); } " (strictly, once in a block)
21
© Peter Andreae COMP 102 4: 21 Expressions /** Convert from fahrenheit to celsius */ public void fahrenheitToCelsius(){ double fahren = UI.askDouble("Fahrenheit:" ); double celsius = (fahren - 32) * 5 / 9; UI.println(fahren + “F is " + celsius + “ C"); } Expressions describe how to compute a value. Expressions are constructed from values variables operators (+, -, *, /, etc) method calls that return a value sub-expressions, using (… ) … + for Strings: "concatenates" the Strings
22
© Peter Andreae COMP 102 4: 22 Method Definition: Like a pad of worksheets public void fahrenToCelsius(){ double fahren = UI.askDouble("Fahrenheit:"); double celsius = (fahren – 32) * 5 / 9; UI.println(fahren + “F is " + celsius + “ C"); } Calling a Method: tempCalc1.fahrenheitToCelsius(); ⇒ get a “copy” of the method worksheet ⇒ perform each action in the body. ⇒ throw the worksheet away (losing all the information on it) Method Calls: a (good) metaphor public void fahrenheitToCelsius(){ double fahren = UI.askDouble("Fahrenheit:"); double celsius = (fahren – 32) * 5 / 9; UI.println(fahren + “ is " + celsius + “ C"); } 86 0 30 0 Fahrenheit:86 86.0F is 30.0C
23
© Peter Andreae COMP 102 4: 23 Summary of Java program structure A Class specifies a type of object TemperatureCalculator.class describes TemperatureCalculator objects A Class contains a constructor Constructor specifies what to do when objects are created A Class contains a collection of methods Each method is an action the objects can perform. TemperatureCalculator objects can do celsiusToFahrenheit, fahrenheitToCelsius, printFormula If you have an object, you can call its methods on it. A constructor/method definitions contains statements Each statement specifies one step of performing the action Method call statements Declaration and Assignment statements
24
© Peter Andreae COMP 102 4: 24 More details: Expressions L-DP-C 2.3 Literal values numbers:9, 5, 76.0034 Strings:“ F ->”, "centigrade = (fahrenheit - 32) *5/9“ … Variables: cent Numerical expressions using arithmetic operators: +, -, *, /, (, ),6 + cent * 45 ordinary arithmetic (except “/” : truncates integers) % “remainder” String expressions using concatenate operator: + Concatenate values into a single String (converts numbers etc into strings)
25
© Peter Andreae COMP 102 4: 25 More Details: Types L-DP-C 2.3 A type is a kind/category of value Every variable must have a type Java has: Primitive types: double-3.495, 6.482E23 int-2358, 45, (integers from -2 billion to 2 billion) longintegers from -2 63 to 2 63 char‘D’, ‘d’, ‘=‘ booleantrue, false byte, short, float: … (see the book for details) Object types: String“Hello John”, “600.45”, “F”, “true” Scanner PrintStream …. (lots of predefined types) TemperatureConverter…. Every class defines a type
26
© Peter Andreae COMP 102 4: 26 Signs of Computer Distress stiffness soreness discomfort weakness tightness heavy tingling numbness aching throbbing burning hot Sore ImmobilityNo blood flow No oxygen to tissue Stop moving Staying still makes muscle fatigue worse. Get moving!
27
© Peter Andreae COMP 102 4: 27 OOS Muscle fatigue/OOS is not an injury: it is a lack of blood supply to muscles Resting or Immobilising sore areas makes pain worse Physical exercise works Get up and get moving! Stretch frequently Seek professional advice
28
© Peter Andreae COMP 102 4: 28 More Details: Expressions Creating a new object: new TemperatureConverter() Methods that return a value... (we will see more soon…) Expressions out of sub expressions (3 * size) + (weight / 2.5)
29
© Peter Andreae COMP 102 4: 29 Method Definitions: Parameters /** Convert from fahrenheit to centigrade */ public void fahrenToCelsius(){ double fahren = UI.askDouble("Fahrenheit:" ); double celsius= (fahren - 32) * 5 / 9; UI.println(“ -> " + celsius + “ C"); } A parameter specifies the type of a value the method needs a name for the place where the value will be put when the method is called (a kind of variable, but special) Parameters are in defined in the headers of method definitions
30
© Peter Andreae COMP 102 4: 30 Method Definition: Like a pad of worksheets public void fahrenToCent(int fahren){ int cent = (fahren – 32) * 5 / 9;.out.println(fahren + “ F -> " + cent + “ C"); } Calling a Method: tempConv1.fahrenToCent(86); ⇒ get a “copy” of the method worksheet ⇒ copy the argument(s) into the parameters(s) ⇒ perform the actions in the body. Method Calls public void fahrenToCent(int fahren){ int cent = (fahren – 32) * 5 / 9; System.out.println(fahren + “ F -> " + cent + “ C"); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.