Download presentation
Presentation is loading. Please wait.
Published byAudrey Willis Modified over 6 years ago
1
Java Coding David Davenport Computer Eng. Dept.,
Syntax for Variables & Constants Input, Output and Assignment a complete Java program David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last updated: 7/10/2017 (Minor updates to code & animations Moved communications/data representation stuff to separate file) Previously: 08/10/2015 (little tidy up & recreated slide messed up by PowerPoint 2013!) Previously: 02/11/2014 (added all communication stuff at end) Previously: 15/10/2014 Previously: 9/10/2012 Previously: 3/10/2010
2
IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.
3
From problem to program…
The story so far... Problem Algorithm Data/Memory requirements Reiterate that data requirements are extracted from the algorithm, not thin air! Done/practiced developing algorithm on the one hand & compiling, debugging & running Java source code on the other. Task now is to translate algorithm & data requirements into Java! Need to know the syntax for programs and each of the concepts mentioned. Since we are now familiar with concepts will present lots of syntax first, then examples. Java Source Code Java bytecode Machine code
4
Need Java Syntax for… Algorithm (in pseudo-code)
Sequence, Decision & Repetition, of Data flow operations Input, Output & Assignment Data/Memory requirements Meaningfully named memory locations Restriction on data (data types) Variables or Constants & initial value Plus comments & methods! Reiterate that data requirements are extracted from the algorithm, not thin air! Done/practiced developing algorithm on the one hand & compiling, debugging & running Java source code on the other. Task now is to translate algorithm & data requirements into Java! Need to know the syntax for programs and each of the concepts mentioned. Since we are now familiar with concepts will present lots of syntax first, then examples. Note: Starting Fall 2010 need to introduce notions of comments & methods briefly here.
5
Comments & White space Comments Syntax:
// any text on remainder of current line /* any text across multiple lines */ /** any text across multiple lines; a Javadoc comment! */ Examples: Java ignores line endings, blanks lines & white space! Use to automatically generate client API from source code. // Author: David. // Date: Oct. 2017 Ignores lines, program can be written on a single line, one word per line or (almost) however you want! Use blank lines & indentation (space or tab characters) to layout as per program logical structure. Note: some places cannot split lines or put extra spaces in Java, e.g. in identifiers, single line comments, relational operators, & string literals. Mention also javadoc comments /** description followed by any text, include tags until */ Run “javadoc MyProg.java“ to generate HTML version of documentation. /* This program blah, blah, blah */ Layout program code for ease of reading!
6
CS101 rule: Names must be meaningful!
Identifiers User-defined names (for variables, constants, methods, etc.) Any sequence of letters, digits and the underscore character only. First character may not be a digit! Upper and lower case are considered different i.e. case sensitive! Cannot use Java reserved words i.e. words such as while, for, class, if, etc. “Dog” not same identifier as “dog” Note that identifiers such as String, System, out, etc are not reserved words and could be used BUT doing so might make your program very confusing since you are redefining commonly used terms. (like me using “dog” to refer to cats, difficult to communicate with other people!) CS101 rule: Names must be meaningful!
7
Data Types For now, use only the following… Primitive Non-primitive
int (for numeric integer, e.g. 5, -27, 0, 510…) double (for numeric real, e.g. 5.75, 3.0, -2.6…) char (for any character, e.g. A, a, B, b, 3, ?, &, … ) boolean (for true / false only) Non-primitive String (for any sequence of zero or more characters e.g. “CS101”, “A”, “Well done!”, … ) Note: Use only these limited Java primitive types & String for now. Will introduce other primitive & non-primitive (object) types later (& discuss them).
8
Declaring Variables Syntax: Type Name (identifier) Examples:
Any Java type Name (identifier) Convention: first letter of embedded words capital, except first! Examples: int age; double area; double initialSpeed; char letterGrade; char lettergrade; String myName; boolean exists; type name; 21 age {int} Notice semicolon – all Java statements end with semicolon. Missing it is syntax error! Variable names cannot have spaces, so a name such as “speed of sound” or “sum of grades so far” cannot be used. Resolve by replacing spaces with “_” (not normally used in Java) or removing spaces which would make reading it difficult so capitalise first letter of each embedded word, except first. E.g. “speedOfSound” & “sumOfGradesSoFar”. CAUTION Java is case sensitive!
9
final type name = value;
Declaring Constants Syntax: Type Any Java type Name (identifier) Convention: all capital letters (& underscore!) Value (literal, variable, constant, expression) Examples: final int SPEEDOFLIGHT = 300; final double PI = 3.142; final String COMPANY = “Bilkent”; final char LETTER_GRADE = ‘A’; final type name = value; Value must be type compatible. final char LETTERGRADE = ‘A’; Note: may also declare constants as static, but this requires them to be defined in the class, not the main method. advantage Naming constants makes maintenance easier. For example, which of these three alternatives would be better if we wished to update PI to 3.0 PI = 3.142; & circumference = 2 * PI * radius; circumference = 2 * * radius; circumference = * radius; Literal values String use “…” char use ‘.’
10
Output (1) Syntax: where output is
Literal value eg. “The area is ”, ‘?’, 12.5, … Named variable or constant eg. area, userName, TAX_RATE, … Expression eg. 2 * PI * radius, “The area is ” + area System.out.println( output ); Value is output exactly as is! Value in named memory location is output Displays “output” on Java console and then moves text cursor to next line. Subsequent output starts there. Will look at expressions in detail shortly. Note: expressions not really needed here, just shortcut, can always use intermediate variables. Resulting value of expression is output Note use of + for string concatenation
11
System.out.print( output );
Use To output the value & leave text cursor on current line. System.out.print( output ); System.out.println( “Welcome to CS101”); System.out.println( “The tax rate is ” + TAXRATE + ‘%’); System.out.println( “Goodbye.”); System.out.println( “Welcome to CS101”); System.out.print( “The tax rate is ”); System.out.print( TAXRATE); System.out.println( ‘%’); System.out.println( “Goodbye.”); How can we display double quotes as part of output? - problem since they terminate string literal! Use escape sequence \” but then how about the back slash character? Again use \\ (look at book for others.) System.out.println(); Start new line!
12
Outline Java Program The CS101 console template… ClassName.java
In Java program = class Classname Convention: first letters capitalised Filename & classname MUST be the same. import java.util.Scanner; /** …description… @author …yourname… @version 1.00, …date… */ public class ClassName { public static void main( String[] args) Scanner scan = new Scanner( System.in); // constants // variables // program code } Don’t worry about details for now. Treat as magic incantation. Say it exactly right & program works! Only important thing is filename & classname must be EXACTLY same. Use this template (copy/paste into your IDE as necessary), all you do is fill-in the blanks. Note: put constants first, then variables, then code for algorithm DEMO - actually declare variables & constants and do some output ******************************************************** Irrelevant now… In Java only have classes (ie. program is a class), same as Robo only methods (ie. program is method) (will see class is collection of methods, i.e. higher level grouping. Collection of classes is package.) Note: Scanner class imported for you! Note: Header comment is in javadoc format! (imports must be before this for some reason)
13
Quick Demo… Creating, compiling, running & debugging a Java program, using the console & a text editor an IDE (Integrated Development Environment) Running Java programs requires only the JRE. try “java –version” from command prompt. Developing Java programs requires the JDK. try “javac –version” from command prompt usually fails… need path to jdk / bin folder! To compile: “javac ProgName.java” {generates ProgName.class assuming it compiles!} To run: “java ProgName” {note this runs the .class file, but do not include in name!} Demo: ? Predict result of running template? + compile template (error, Filename!) + correct and try again… then run. + output of literal values + defining constants & variables + assigning value to constant (error!) + putting int into double and vice versa (another error!) JRE ~Java Runtime Environment (the Java interpreter, java.exe, and libraries!) JDK ~Java Development Kit (the Java compiler, javac.exe, and other tools)
14
Syntax for Input and assignment statements.
More Syntax…
15
Input Syntax: Examples StringVariable = scan.next();
intVariable = scan.nextInt(); doubleVariable = scan.nextDouble(); userName = scan.next(); age = scan.nextInt(); salary = scan.nextDouble(); str = scan.nextLine(); Actually an assignment statement too! Program stops on reaching such a statement and waits for user to press ENTER (end of line) It then takes the user input and stores it in the specified variable. Requires “import java.util.Scanner;” at start of program (included in CS101 template) & “Scanner scan = new Scanner( System.in);” in method before use! NOTE: Scanner splits input stream up at whitespace boundaries by default. This means next() gets a word, and nextInt() may leave text on current line. nextLine() gets rest of current line. USE: scan.useDelimiter( System.getProperty( "line.separator") ); to break on line rather than on whitespace boundaries. Can also use to read from string, files or url’s. But may need exception handling, for example “throws java.io.IOException” added to method (usually main) next() returns the next (String) token, normally a word –when using default delimiters. Can tokenize input using different chars & regular expressions. Locale sensitive! – common problem user enters Turkish values, but machine is in English locale for example, 23,75 vs Scanner class includes hasNext(), hasNextInt(), hasNextDouble(), etc. Can’t use “scan.nextChar()” use “scan.nextLine().charAt(0)” instead? Note: Problem of reading String after number, eg. i = scan.nextInt(); s = scan.nextLine(); will usually give an empty String s! add extra scan.nextLine(); inbetween so as to consume \n character. Variables must be declared before use Standard from Java5.0 on Invalid input may give run-time error! Program must include: import java.util.Scanner; Scanner scan = new Scanner( System.in);
16
Assignment Syntax: where expression is & resultVariable = expression;
… is assigned the result of … Syntax: where expression is operand or operand operator operand & Operand is Literal value Named Variable or constant Result of method call Expression (can use brackets to disambiguate)! Operator is +, -, *, /, % (modulus, remainder after integer division) resultVariable = expression; Result of expression must be of suitable type to put into resultVariable! Expression is evaluated and the result placed in the resultVariable Note can also use + & - as unary operators. Can use brackets to disambiguate! Increment/decrement operators ++ & -- too! -use only in single statements. Also shortcut assignment operators : +=, -=, *=, /= & %= {but do not use!}
17
… is assigned the result of …
Assignment … is assigned the result of … Examples What is the result of this? Evaluation rules Bracketed sub-expressions first Operator precedence ( * / % before + - ) Left to right total = 0; x = y; sum = firstNumber + secondNumber; netPay = grossPay * ( 1 – TAX_RATE/100); count = count + 1; c = Math.sqrt( a * a + b * b ); Note that assignment statements are not arithmetic equations, eg. count = count + 1 is nonsense. DEMO this and input too… May talk about type compatibility here or leave to later discussion…? e.g. try d = i; // ok, but i = d; // not ok! can force with i = (int) d; // typecast! Type compatibility… can put narrower types into wider ones since (usually) no danger of loss, eg. int into long or double. [loss of significant digits!] going the other way is dangerous (serious loss of info.) & so compiler issues error message. can use type cast to force compiler to accept (– but may fail at run time?) useful when dividing two ints since result type is int not real! double = (double) int/int; 4 + 2 / 3 – 1
18
The complete Circle Computer program.
A complete example…
19
A Complete Example (1) Problem – find area & circumference… Algorithm
Data requirements Print welcome message Ask for & get radius from user Compute area as pi.radius.radius Compute circumference as 2.pi.radius Report area, circumference & radius Using the previously developed algorithm, extract data requirements from it. Note all these values are local to program/method L radius - int L area, circumference - double PI – double, constant = 3.142
20
The CS101 console template…
ClassName.java import java.util.Scanner; /** …description… @author …yourname… @version 1.00, …date… */ public class ClassName { public static void main( String[] args) Scanner scan = new Scanner( System.in); // constants // variables // program code } Again, start with the cs101 console template Don’t worry about details for now. Treat as magic incantation. Say it exactly right & program works! Only important thing is filename & classname must be EXACTLY same. Use this template (copy/paste into your IDE as necessary), all you do is fill-in the blanks. Note: put constants first, then variables, then code for algorithm DEMO - actually declare variables & constants and do some output ******************************************************** Irrelevant now… In Java only have classes (ie. program is a class), same as Robo only methods (ie. program is method) (will see class is collection of methods, i.e. higher level grouping. Collection of classes is package.) Note: Scanner class imported for you! Note: Header comment is in javadoc format! (imports must be before this for some reason)
21
The CS101 console template…
CirleComputer.java import java.util.Scanner; /** Report area & circumference of circle of radius given by user. @author David @version 1.00, 2017/10/17 */ public class CircleComputer { public static void main( String[] args) Scanner scan = new Scanner( System.in); // constants // variables // program code } Edit header comment… change the ClassName & save. Don’t worry about details for now. Treat as magic incantation. Say it exactly right & program works! Only important thing is filename & classname must be EXACTLY same. Use this template (copy/paste into your IDE as necessary), all you do is fill-in the blanks. Note: put constants first, then variables, then code for algorithm DEMO - actually declare variables & constants and do some output ******************************************************** Irrelevant now… In Java only have classes (ie. program is a class), same as Robo only methods (ie. program is method) (will see class is collection of methods, i.e. higher level grouping. Collection of classes is package.) Note: Scanner class imported for you! Note: Header comment is in javadoc format! (imports must be before this for some reason)
22
The CS101 console template…
CircleComputer.java : public class CircleComputer { public static void main( String[] args) Scanner scan = new Scanner( System.in); // constants // variables // program code // 1. Print welcome message // 2. Ask for & get radius from user // 3. Compute area as pi.radius.radius // 4. Compute circumference as 2.pi.radius // 5. Report area, circumference & radius } Don’t worry about details for now. Treat as magic incantation. Say it exactly right & program works! Only important thing is filename & classname must be EXACTLY same. Use this template (copy/paste into your IDE as necessary), all you do is fill-in the blanks. Note: put constants first, then variables, then code for algorithm DEMO - actually declare variables & constants and do some output ******************************************************** Irrelevant now… In Java only have classes (ie. program is a class), same as Robo only methods (ie. program is method) (will see class is collection of methods, i.e. higher level grouping. Collection of classes is package.) Note: Scanner class imported for you! Note: Header comment is in javadoc format! (imports must be before this for some reason) include algorithm steps as comments & save again!
23
A Complete Example (3) CircleComputer.java
Header comment edited to include program description, author name & date. import java.util.Scanner; /** * Report area & circumference of circle of radius given by user. * David 1.00, 2017/10/07 */ public class CircleComputer { public static void main( String[] args) Scanner scan = new Scanner( System.in); // constants final double PI = 3.142; // variables int radius; double area; double circumference; ClassName edited and file saved with .java extension. & algorithm steps added as comments. Note: sequence is achieved simply by writing program statements one after the other! Note steps 2 & 5 written according to expanded algorithms developed previously. Normally larger steps would be written in methods (with their own data requirements) (in step 2 variables would be outputs, in step 5 outputs, in 3 radius is input area output, in 4 radius input circumference output.) Now need syntax for decision, repetition, & methods! Include Java code for constants & variables
24
Put a blank line between logical sections
A Complete Example (3) // 1. Print welcome message System.out.println( "Welcome to Circle Computer."); // 2. Ask for & get radius from user System.out.print( "Please enter the radius: "); radius = scan.nextInt(); // 3. Compute area as pi.radius.radius area = PI * radius * radius; // 4. Compute circumference as 2.pi.radius circumference = 2 * PI * radius; // 5. Report area, circumference & radius System.out.print( "The area of a circle of radius "); System.out.print( radius); System.out.print( " is "); System.out.println( area); System.out.print( "and its circumference is "); System.out.print( circumference); System.out.println(); } } // end class CircleComputer add Java code for each algorithm step Indentation Put a blank line between logical sections Note: sequence is achieved simply by writing program statements one after the other! Note steps 2 & 5 written according to expanded algorithms developed previously. Normally these would be written in methods (with their own data requirements) (in step 2 variables would be outputs, in step 5 outputs, in 3 radius is input area output, in 4 radius input circumference output.) Now need syntax for decision, repetition, & methods! Suggest actually compile & execute this then run with various inputs, e.g. 5, 4, 6, 4.5, test Note steps 2 & 5 expanded as per original algorithm. Save… Compile… & Run!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.