By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. For example, variable-name identifier firstNumber has a capital N in its second word, Number.
99 trang |
Chia sẻ: huyhoang44 | Lượt xem: 966 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Introductionto java applications, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
2Introductionto Java Applications1 What’s in a name? that which we call a rose By any other name would smell as sweet.William ShakespeareWhen faced with a decision, I always ask, “What would be the most fun?”Peggy Walker“Take some more tea,” the March Hare said to Alice, very earnestly. “I’ve had nothing yet,” Alice replied in an offended tone: “so I can’t take more.” “You mean you can’t take less,” said the Hatter: “it’s very easy to take more than nothing.”Lewis Carroll2OBJECTIVESIn this chapter you will learn: To write simple Java applications.To use input and output statements.Java’s primitive types.Basic memory concepts.To use arithmetic operators.The precedence of arithmetic operators.To write decision-making statements.To use relational and equality operators.32.1 Introduction2.2 First Program in Java: Printing a Line of Text2.3 Modifying Our First Java Program2.4 Displaying Text with printf2.5 Another Java Application: Adding Integers2.6 Memory Concepts2.7 Arithmetic2.8 Decision Making: Equality and Relational Operators2.9 (Optional) Software Engineering Case Study: Examining the Requirements Document2.10 Wrap-Up42.1 IntroductionJava application programmingDisplay messagesObtain information from the userArithmetic calculationsDecision-making fundamentals52.2 First Program in Java: Printing a Line of TextApplicationExecutes when you use the java command to launch the Java Virtual Machine (JVM)Sample programDisplays a line of textIllustrates several important Java language features6OutlineWelcome1.java72.2 First Program in Java: Printing a Line of Text (Cont.)Comments start with: //Comments ignored during program executionDocument and describe codeProvides code readabilityTraditional comments: /* ... */ /* This is a traditional comment. It can be split over many lines */Another line of commentsNote: line numbers not part of program, added for reference1 // Fig. 2.1: Welcome1.java2 // Text-printing program. 8Common Programming Error 2.1Forgetting one of the delimiters of a traditional or Javadoc comment is a syntax error. The syntax of a programming language specifies the rules for creating a proper program in that language. A syntax error occurs when the compiler encounters code that violates Java’s language rules (i.e., its syntax). In this case, the compiler does not produce a .class file. Instead, the compiler issues an error message to help the programmer identify and fix the incorrect code. Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them during the compilation phase. You will be unable to execute your program until you correct all the syntax errors in it.9Good Programming Practice 2.1Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program was last modified. (We are not showing the author, date and time in this book’s programs because this information would be redundant.)102.2 First Program in Java: Printing a Line of Text (Cont.)Blank lineMakes program more readableBlank lines, spaces, and tabs are white-space charactersIgnored by compilerBegins class declaration for class Welcome1Every Java program has at least one user-defined classKeyword: words reserved for use by Javaclass keyword followed by class nameNaming classes: capitalize every wordSampleClassName3 4 public class Welcome1 11Good Programming Practice 2.2Use blank lines and space characters to enhance program readability.122.2 First Program in Java: Printing a Line of Text (Cont.)Java identifierSeries of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ )Does not begin with a digit, has no spacesExamples: Welcome1, $value, _value, button77button is invalidJava is case sensitive (capitalization matters) a1 and A1 are differentIn chapters 2 to 7, start each class with public classDetails of this covered later4 public class Welcome1 13Good Programming Practice 2.3By convention, always begin a class name’s identifier with a capital letter and start each subsequent word in the identifier with a capital letter. Java programmers know that such identifiers normally represent Java classes, so naming your classes in this manner makes your programs more readable.14Common Programming Error 2.2Java is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error. 152.2 First Program in Java: Printing a Line of Text (Cont.)Saving filesFile name must be class name with .java extensionWelcome1.javaLeft brace {Begins body of every classRight brace ends declarations (line 13)4 public class Welcome1 5 { 16Common Programming Error 2.3It is an error for a public class to have a file name that is not identical to the class name (plus the .java extension) in terms of both spelling and capitalization.17Common Programming Error 2.4It is an error not to end a file name with the .java extension for a file containing a class declaration. If that extension is missing, the Java compiler will not be able to compile the class declaration.18Good Programming Practice 2.4Whenever you type an opening left brace, {, in your program, immediately type the closing right brace, }, then reposition the cursor between the braces and indent to begin typing the body. This practice helps prevent errors due to missing braces.19Good Programming Practice 2.5Indent the entire body of each class declaration one “level” of indentation between the left brace, {, and the right brace, }, that delimit the body of the class. This format emphasizes the class declaration's structure and makes it easier to read.20Good Programming Practice 2.6Set a convention for the indent size you prefer, and then uniformly apply that convention. The Tab key may be used to create indents, but tab stops vary among text editors. We recommend using three spaces to form a level of indent.21Common Programming Error 2.5It is a syntax error if braces do not occur in matching pairs.222.2 First Program in Java: Printing a Line of Text (Cont.)Part of every Java applicationApplications begin executing at mainParentheses indicate main is a method (Ch. 3 and 6)Java applications contain one or more methodsExactly one method must be called mainMethods can perform tasks and return informationvoid means main returns no informationFor now, mimic main's first lineLeft brace begins body of method declarationEnded by right brace } (line 11)7 public static void main( String args[] )8 { 23Good Programming Practice 2.7Indent the entire body of each method declaration one “level” of indentation between the left brace, {, and the right brace, }, that define the body of the method. This format makes the structure of the method stand out and makes the method declaration easier to read.242.2 First Program in Java: Printing a Line of Text (Cont.)Instructs computer to perform an actionPrints string of characters String – series of characters inside double quotesWhite-spaces in strings are not ignored by compilerSystem.outStandard output objectPrint to command window (i.e., MS-DOS prompt)Method System.out.println Displays line of textThis line known as a statementStatements must end with semicolon ;9 System.out.println( "Welcome to Java Programming!" );25Common Programming Error 2.6Omitting the semicolon at the end of a statement is a syntax error.26Error-Prevention Tip 2.1When learning how to program, sometimes it is helpful to “break” a working program so you can familiarize yourself with the compiler's syntax-error messages. These messages do not always state the exact problem in the code. When you encounter such syntax-error messages in the future, you will have an idea of what caused the error. Try removing a semicolon or brace from the program of Fig. 2.1, then recompile the program to see the error messages generated by the omission.27Error-Prevention Tip 2.2When the compiler reports a syntax error, the error may not be on the line number indicated by the error message. First, check the line for which the error was reported. If that line does not contain syntax errors, check several preceding lines.282.2 First Program in Java: Printing a Line of Text (Cont.)Ends method declarationEnds class declarationCan add comments to keep track of ending braces11 } // end method main13 } // end class Welcome129Good Programming Practice 2.8Following the closing right brace (}) of a method body or class declaration with an end-of-line comment indicating the method or class declaration to which the brace belongs improves program readability.302.2 First Program in Java: Printing a Line of Text (Cont.)Compiling a programOpen a command prompt window, go to directory where program is storedType javac Welcome1.javaIf no syntax errors, Welcome1.class createdHas bytecodes that represent applicationBytecodes passed to JVM31Error-Prevention Tip 2.3When attempting to compile a program, if you receive a message such as “bad command or filename,” “javac: command not found” or “'javac' is not recognized as an internal or external command, operable program or batch file,” then your Java software installation was not completed properly. If you are using the Java Development Kit, this indicates that the system’s PATH environment variable was not set properly. Please review the installation instructions in the Before You Begin section of this book carefully. On some systems, after correcting the PATH, you may need to reboot your computer or open a new command window for these settings to take effect.32Error-Prevention Tip 2.4The Java compiler generates syntax-error messages when the syntax of a program is incorrect. Each error message contains the file name and line number where the error occurred. For example, Welcome1.java:6 indicates that an error occurred in the file Welcome1.java at line 6. The remainder of the error message provides information about the syntax error.33Error-Prevention Tip 2.5The compiler error message “Public class ClassName must be defined in a file called ClassName.java” indicates that the file name does not exactly match the name of the public class in the file or that you typed the class name incorrectly when compiling the class.342.2 First Program in Java: Printing a Line of Text (Cont.)Executing a programType java Welcome1Launches JVMJVM loads .class file for class Welcome1.class extension omitted from commandJVM calls method main35Fig. 2.2 | Executing Welcome1 in a Microsoft Windows XP Command Prompt window.You type this command to execute the applicationThe program outputsWelcome to Java Programming!36Error-Prevention Tip 2.6When attempting to run a Java program, if you receive a message such as “Exception in thread "main" java.lang.NoClassDefFoundError: Welcome1,” your CLASSPATH environment variable has not been set properly. Please review the installation instructions in the Before You Begin section of this book carefully. On some systems, you may need to reboot your computer or open a new command window after configuring the CLASSPATH.372.3 Modifying Our First Java ProgramModify example in Fig. 2.1 to print same contents using different code382.3 Modifying Our First Java Program (Cont.)Modifying programsWelcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1)Using different codeLine 9 displays “Welcome to ” with cursor remaining on printed lineLine 10 displays “Java Programming! ” on same line with cursor on next line 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );39OutlineWelcome2.java1. Comments2. Blank line3. Begin class Welcome23.1 Method main4. Method System.out.print4.1 Method System.out.println5. end main, Welcome2Program OutputSystem.out.print keeps the cursor on the same line, so System.out.println continues on the same line. 402.3 Modifying Our First Java Program (Cont.)Escape charactersBackslash ( \ )Indicates special characters to be outputNewline characters (\n)Interpreted as “special characters” by methods System.out.print and System.out.printlnIndicates cursor should be at the beginning of the next lineWelcome3.java (Fig. 2.4)Line breaks at \n9 System.out.println( "Welcome\nto\nJava\nProgramming!" );41OutlineWelcome3.java1. main2. System.out.println (uses \n for new line)Program OutputA new line begins after each \n escape sequence is output.42Fig. 2.5 | Some common escape sequences.432.4 Displaying Text with printfSystem.out.printfFeature added in Java SE 5.0Displays formatted dataFormat stringFixed textFormat specifier – placeholder for a valueFormat specifier %s – placeholder for a string 9 System.out.printf( "%s\n%s\n", 10 "Welcome to", "Java Programming!" );44OutlineWelcome4.javamainprintfProgram outputSystem.out.printf displays formatted data. 45Good Programming Practice 2.9Place a space after each comma (,) in an argument list to make programs more readable.46Common Programming Error 2.7Splitting a statement in the middle of an identifier or a string is a syntax error.472.5 Another Java Application: Adding IntegersUpcoming programUse Scanner to read two integers from userUse printf to display sum of the two valuesUse packages48OutlineAddition.java(1 of 2)import declarationScannernextIntimport declaration imports class Scanner from package java.util. Declare and initialize variable input, which is a Scanner. Declare variables number1, number2 and sum. Read an integer from the user and assign it to number1. 49OutlineAddition.java(2 of 2)4. Addition5. printfRead an integer from the user and assign it to number2. Calculate the sum of the variables number1 and number2, assign result to sum.Display the sum using formatted output. Two integers entered by the user. 502.5 Another Java Application: Adding Integers (Cont.)import declarations Used by compiler to identify and locate classes used in Java programsTells compiler to load class Scanner from java.util packageBegins public class AdditionRecall that file name must be Addition.javaLines 8-9: begin main3 import java.util.Scanner; // program uses class Scanner5 public class Addition 6 {51Common Programming Error 2.8All import declarations must appear before the first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error.52Error-Prevention Tip 2.7Forgetting to include an import declaration for a class used in your program typically results in a compilation error containing a message such as “cannot resolve symbol.” When this occurs, check that you provided the proper import declarations and that the names in the import declarations are spelled correctly, including proper use of uppercase and lowercase letters.532.5 Another Java Application: Adding Integers (Cont.)Variable Declaration StatementVariablesLocation in memory that stores a valueDeclare with name and type before useInput is of type Scanner Enables a program to read data for use Variable name: any valid identifierDeclarations end with semicolons ;Initialize variable in its declarationEqual signStandard input objectSystem.in10 // create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in );542.5 Another Java Application: Adding Integers (Cont.)Declare variable number1, number2 and sum of type intint holds integer values (whole numbers): i.e., 0, -4, 97Types float and double can hold decimal numbersType char can hold a single character: i.e., x, $, \n, 7int, float, double and char are primitive typesCan add comments to describe purpose of variablesCan declare multiple variables of the same type in one declarationUse comma-separated list13 int number1; // first number to add14 int number2; // second number to add15 int sum; // sum of number 1 and number 2 int number1, // first number to add number2, // second number to add sum; // sum of number1 and number255Good Programming Practice 2.10Declare each variable on a separate line. This format allows a descriptive comment to be easily inserted next to each declaration.56Good Programming Practice 2.11Choosing meaningful variable names helps a program to be self-documenting (i.e., one can understand the program simply by reading it rather than by reading manuals or viewing an excessive number of comments).57Good Programming Practice 2.12By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. For example, variable-name identifier firstNumber has a capital N in its second word, Number.582.5 Another Java Application: Adding Integers (Cont.)Message called a prompt - directs user to perform an actionPackage java.langResult of call to nextInt given to number1 using assignment operator =Assignment statement= binary operator - takes two operandsExpression on right evaluated and assigned to variable on leftRead as: number1 gets the value of input.nextInt()17 System.out.print( "Enter first integer: " ); // prompt18 number1 = input.nextInt(); // read first number from user59Software Engineering Observation 2.1By default, package java.lang is imported in every Java program; thus, java.lang is the only package in the Java API that does not require an import declaration.60Good Programming Practice 2.13Place spaces on either side of a binary operator to make it stand out and make the program more readable.612.5 Another Java Application: Adding Integers (Cont.)Similar to previous statementPrompts the user to input the second integerSimilar to previous statementAssign variable number2 to second integer inputAssignment statementCalculates sum of number1 and number2 (right hand side)Uses assignment operator = to assign result to variable sumRead as: sum gets the value of number1 + number2number1 and number2 are operands20 System.out.print( "Enter second integer: " ); // prompt21 number2 = input.nextInt(); // read second number from user23 sum = number1 + number2; // add numbers622.5 Another Java Application: Adding Integers (Cont.)Use System.out.printf to display resultsFormat specifier %dPlaceholder for an int valueCalculations can also be performed inside printfParentheses around the expression number1 + number2 are not required25 System.out.printf( "Sum is %d\n: " , sum ); // display sum System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) ); 632.6 Memory ConceptsVariables Every variable has a name, a type, a size and a valueName corresponds to location in memoryWhen new value is placed into a variable, replaces (and destroys) previous value Reading variables from memory does not change them64Fig. 2.8 | Memory location showing the name and value of variable number1.65Fig. 2.9 | Memory locations after storing values for number1 and number2.66Fig. 2.10 | Memory locations after calculating and storing the sum of number1 and number2. 672.7 ArithmeticArithmetic calculations used in most programsUsage * for multiplication / for division% for remainder+, -Integer division truncates remainder7 / 5 evaluates to 1Remainder operator % returns the remainder 7 % 5 evaluates to 268Fig. 2.11 | Arithmetic operators.692.7 Arithmetic (Cont.)Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition)Use parenthesis when neededExample: Find the average of three variables a, b and cDo not use: a + b + c / 3 Use: ( a + b + c ) / 370Fig. 2.12 | Precedence of arithmetic operators.71Good Programming Practice 2.14Using parentheses for complex arithmetic expressions, even when the parentheses are not necessary, can make the arithmetic expressions easier to read.72Fig. 2.13 | Order in which a second-degree polynomial is evaluated.732.8 Decision Making: Equality and Relational OperatorsConditionExpression can be either true or falseif statementSimple version in this section, more detail laterIf a condition is true, then the body of the if statement executedControl always resumes after the if statementConditions in if statements can be formed using equality or relational operators (next slide)74Fig. 2.14 | Equality and relational operators. 75OutlineComparison.java(1 of 2)1. Class Comparison1.1 main1.2 Declarations1.3 Input data (nextInt)1.4 Compare two inputs using if statementsTest for equality, display result using printf.Compares two numbers using relational operator , =.772.8 Decision Making: Equality and Relational Operators (Cont.)Line 6: begins class Comparison declarationLine 12: declares Scanner variable input and assigns it a Scanner that inputs data from the standard inputLines 14-15: declare int variablesLines 17-18: prompt the user to enter the first integer and input the valueLines 20-21: prompt the user to enter the second integer and input the value782.8 Decision Making: Equality and Relational Operators (Cont.)if statement to test for equality using (==)If variables equal (condition true) Line 24 executesIf variables not equal, statement skippedNo semicolon at the end of line 23Empty statementNo task is performedLines 26-27, 29-30, 32-33, 35-36 and 38-39Compare number1 and number2 with the operators !=, , =, respectively23 if ( number1 == number2 ) 24 System.out.printf( "%d == %d\n", number1, number2 );79Common Programming Error 2.9Forgetting the left and/or right parentheses for the condition in an if statement is a syntax error—the parentheses are required.80Common Programming Error 2.10Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error. The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.” To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”81Common Programming Error 2.11It is a syntax error if the operators ==, !=, >= and = and = and and =<, is a syntax error.83Good Programming Practice 2.15Indent an if statement’s body to make it stand out and to enhance program readability.84Good Programming Practice 2.16Place only one statement per line in a program. This format enhances program readability.85Common Programming Error 2.13Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error.86Good Programming Practice 2.17A lengthy statement can be spread over several lines. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines until the end of the statement.87Good Programming Practice 2.18Refer to the operator precedence chart (see the complete chart in Appendix A) when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, exactly as you would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right.88Fig. 2.16 | Precedence and associativity of operations discussed. 892.9 (Optional) Software Engineering Case Study: Examining the Requirements DocumentObject-oriented design (OOD) process using UMLChapters 3 to 8, 10Object-oriented programming (OOP) implementationAppendix J902.9 (Optional) Software Engineering Case Study (Cont.)Requirements DocumentNew automated teller machine (ATM)Allows basic financial transactionView balance, withdraw cash, deposit fundsUser interfaceDisplay screen, keypad, cash dispenser, deposit slotATM sessionAuthenticate user, execute financial transaction91Fig. 2.17 | Automated teller machine user interface.92Fig. 2.18 | ATM main menu.93Fig. 2.19 | ATM withdrawal menu.942.9 (Optional) Software Engineering Case Study (Cont.)Analyzing the ATM SystemRequirements gatheringSoftware life cycleWaterfall modelInteractive modelUse case modelingUse case DiagramModel the interactions between clients and its use casesActorExternal entity95Fig. 2.20 | Use case diagram for the ATM system from the user's perspective.96Fig. 2.21 | Use case diagram for a modified version of our ATM system that also allows users to transfer money between accounts.972.9 (Optional) Software Engineering Case Study (Cont.)UML diagram typesModel system structureClass diagramModels classes, or “building blocks” of a systemscreen, keypad, cash dispenser, deposit slot.982.9 (Optional) Software Engineering Case Study (Cont.)Model system behaviorUse case diagrams Model interactions between user and a systemState machine diagramsModel the ways in which an object changes state Activity diagramsModels an object’s activity during program executionCommunication diagrams (collaboration diagrams)Models the interactions among objectsEmphasize what interactions occurSequence diagrams Models the interactions among objectsEmphasize when interactions occur99
Các file đính kèm theo tài liệu này:
- javahtp7e_02_7421_2881.ppt