Kiến trúc máy tính và hợp ngữ - Chapter 5: Java syntax and style

Braces mark nested blocks. Braces indicate that the statements within them form one compound statement. Statements inside a block are indented, usually by two spaces or one tab.

ppt24 trang | Chia sẻ: huyhoang44 | Lượt xem: 717 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kiến trúc máy tính và hợp ngữ - Chapter 5: Java syntax and style, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Java Syntax and Style/** * Chapter 5 */Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.Java MethodsObject-Oriented Programmingand Data StructuresMaria Litvin ● Gary Litvin2nd AP edition  with GridWorld1Objectives:Learn to distinguish the required Java syntax from the conventional styleLearn when to use comments and how to mark themReview reserved words and standard namesLearn the proper style for naming classes, methods, and variablesLearn to space and indent blocks of code2CommentsComments are notes in plain English inserted in the source code.Comments are used to:document the program’s purpose, author, revision history, copyright notices, etc.describe fields, constructors, and methodsexplain obscure or unusual places in the codetemporarily “comment out” fragments of code3Formats for CommentsA “block” comment is placed between /* and */ marks:A single-line comment goes from // to the end of the line:/* Exercise 5-2 for Java Methods Author: Miss Brace Date: 3/5/2015 Rev. 1.0 */weight *= 2.2046; // Convert to kilograms4Javadoc CommentsUsed by the JDK’s special utility program javadoc to automatically generate documentation in HTML format from the source codeShould precede a class, a method, or a fieldCan use special javadoc tags:@param – describes a parameter of a method @return - describes the method’s return value5Javadoc Comments (cont’d)/** * Returns total sales from all vendors; * sets totalSales * to 0. * * @return total amount of sales from all vendors *//** indicates a javadoc commentCan use HTML tagsCommon style6Reserved WordsIn Java a number of words are reserved for a special purpose.Reserved words use only lowercase letters.Reserved words include:primitive data types: int, double, char, boolean, etc.storage modifiers: public, private, static, final, etc.control statements: if, else, switch, while, for, etc.built-in constants: true, false, nullThere are about 50 reserved words total. 7Programmer-Defined NamesIn addition to reserved words, Java uses standard names for library packages and classes:String, Graphics, JFrame, JButton,java.awt, javax.swingThe programmer gives names to his or her classes, methods, fields, and variables.8Names (cont’d)Syntax: A name can include: upper- and lowercase lettersdigitsunderscore charactersSyntax: A name cannot begin with a digit.Style: Names should be descriptive to improve readability.9Names (cont’d)Programmers follow strict style conventions.Style: names of classes begin with an uppercase letter, subsequent words are capitalized:public class ActorWorld Style: names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized:private int sideLength;public void moveTo()10Names (cont’d)Method names often sound like verbs:setBackground, getText, moveForward, stopField names often sound like nouns:color, steps, button, controlPanelConstants often use all caps:PI, PIXELS_PER_INCHIt is OK to use short names for temporary “throwaway” variables:i, k, x, y, str11Syntax vs. StyleSyntax is part of the language. The compiler checks it.Style is a convention widely adopted by software professionals.The main purpose of style is to improve the readability of programs.12SyntaxThe compiler catches syntax errors and generates error messages.Text in comments and literal strings within double quotes are excluded from syntax checking.Before compiling, carefully read your code a couple of times to check for syntax and logic errors.13Syntax (cont’d)Pay attention to and check for:matching braces { }, parentheses ( ), and brackets [ ]missing or extraneous semicolonscorrect symbols for operators+, -, =, <, <=, ==, ++, &&, etc.correct spelling of reserved words, library names and programmer-defined names, including upper/lower case14Syntax (cont’d)Common syntax errors:Missing closing brace Public static int abs (int x) { If (x < 0); { x = -x } return x; public static int sqrt (int x) ...Extraneous semicolonSpelling (p  P, if  If)Missing semicolon15StyleArrange statements on separate linesInsert blank lines between fragments of code.Indent code within braces.Use comments judiciously: comment constructors, methods, fields, important steps, but not every statement in the program.16 public void act() { if (steps < sideLength && canMove()) { move(); steps++; } else { turn(); turn(); steps = 0; } }Style (cont’d)Compiles finepublic void act(){if(steps< sideLength&&canMove()){move();steps++;}else{turn();turn(); steps=0;}}A little more readable17Style (cont’d)public void fill (char ch){ int rows = grid.length, cols = grid[0].length; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { grid[r][c] = ch; } }}Add blank lines for readabilityAdd spaces around operators and after semicolons18Blocks, IndentationJava code consists mainly of declarations and control statements.Declarations describe objects and methods.Control statement describe actions.Declarations and control statements end with a semicolon.No semicolon is used after a closing brace (except in certain array declarations).19Blocks, Indentation (cont’d)Braces mark nested blocks.Braces indicate that the statements within them form one compound statement.Statements inside a block are indented, usually by two spaces or one tab.20 private static void merge(double[] a, int from, int middle, int to) { int i = from, j = middle + 1, k = from; while (i <= middle && j <= to) { if (a[i] < a[j]) { temp[k] = a[i]; i++; } else { temp[k] = a[j]; j++; } k++; } ... }One compound statementMethod’s bodyOne compound statementOne compound statement21Review:Name as many uses of comments as you can.What does the javadoc program do?Explain the difference between syntax and style.Why is style important?Roughly how many reserved words does Java have?22Review (cont’d):Explain the convention for naming classes, methods, and variables.Which of the following are syntactically valid names for variables: C, _denom_, my.num, AvgScore, count1, 7seas? Which of them are in good style?What can happen if you put an extra semicolon in your program?23Review (cont’d):What are braces used for in Java?Is indentation required by Java syntax or style?24

Các file đính kèm theo tài liệu này:

  • pptch05_6437.ppt