Advanced Programming Language - Chapter I: Fundamentals Of Programming

The com directory does not have to be the root directory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Suppose the com directory is under c:\book. The following line adds c:\book into the classpath: classpath=.;c:\book; The period (.) indicating the current directory is always in classpath. The directory c:\book is in classpath so that you can use the package com.prenhall.mypackage in the program.

pdf139 trang | Chia sẻ: dntpro1256 | Lượt xem: 786 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Advanced Programming Language - Chapter I: Fundamentals Of Programming, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
ys. What day is in 10 days? You can find that day is Tuesday using the following expression: Saturday is the 6th day in a week A week has 7 days January has 31 days The 2nd day in a week is Tuesday (6 + 31) % 7 is 2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 37 Scientific Notation Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 38 Arithmetic Expressions )94(9))(5(10 5 43 y x xx cbayx      is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 39 Example: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: )32)(( 95  fahrenheitcelsius Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 40 Shortcut Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 41 Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 42 Increment and Decrement Operators, cont. int i = 10; int newNum = 10 * i++; int newNum = 10 * i; i = i + 1; Same effect as int i = 10; int newNum = 10 * (++i); i = i + 1; int newNum = 10 * i; Same effect as Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 43 Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times Such as this: int k = ++i + i. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 44 Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 45 Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 46 Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 47 Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong? int x = 5 / 2.0; byte, short, int, long, float, double range increases Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 48 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Four hexadecimal digits. NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b char ch = 'a'; System.out.println(++ch); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 49 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 50 Example: Displaying Unicodes Write a program that displays two Chinese characters and three Greek letters. DisplayUnicode Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 51 Escape Sequences for Special Characters Description Escape Sequence Unicode Backspace \b \u0008 Tab \t \u0009 Linefeed \n \u000A Carriage return \r \u000D Backslash \\ \u005C Single Quote \' \u0027 Double Quote \" \u0022 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 52 Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 53 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 54 Casting between char and Numeric Types int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 55 The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the System class and JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in Chapter 6, “Classes and Objects.” For the time being, you just need to know how to declare a String variable, how to assign a string to the variable, and how to concatenate strings. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 56 String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s becomes SupplementB Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 57 Obtaining Input 1. Using JOptionPane input dialogs 2. Using Scanner class Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 58 Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE)); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 59 Two Ways to Invoke the Method There are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it. One is to use a statement as shown in the example: String string = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE)); where x is a string for the prompting message, and y is a string for the title of the input dialog box. The other is to use a statement like this: JOptionPane.showInputDialog(x); where x is a string for the prompting message. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 60 Converting Strings to Integers The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 61 Converting Strings to Doubles To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 62 Example: Computing Loan Payments ComputeLoan Run This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment. 12)1( 11    arsnumberOfYeerestRatemonthlyInt erestRatemonthlyIntloanAmount Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 63 Example: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. ComputeChange Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 64 Example: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19. The currentTimeMillis method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT. (1970 was the year when the Unix operating system was formally introduced.) You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows. ShowCurrentTime Run Elapsed time Unix Epoch 01-01-1970 00:00:00 GMT Current Time Time System.CurrentTimeMills() Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 65 Getting Input Using Scanner 1. Create a Scanner object Scanner scanner = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, System.out.print("Enter a double value: "); Scanner scanner = new Scanner(System.in); double d = scanner.nextDouble(); TestScanner Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 66 Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 67 Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instructor, date, and a brief description at the beginning of the program. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 68 Naming Conventions Choose meaningful and descriptive names. Variables and method names – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 69 Naming Conventions, cont.  Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea.  Constants: – Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 70 Proper Indentation and Spacing  Indentation – Indent two spaces. Spacing – Use blank line to separate segments of the code. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 71 Block Styles Use end-of-line style for braces. public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } End-of-line style Next-line style Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 72 The boolean Type and Operators Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. boolean b = (1 > 2); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 73 Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 74 Boolean Operators Operator Name ! not && and || or ^ exclusive or Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 75 Examples System.out.println("Is " + num + " divisible by 2 and 3? " + ((num % 2 == 0) && (num % 3 == 0))); System.out.println("Is " + num + " divisible by 2 or 3? " + ((num % 2 == 0) || (num % 3 == 0))); System.out.println("Is " + num + " divisible by 2 or 3, but not both? " + ((num % 2 == 0) ^ (num % 3 == 0))); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 76 Example: Determining Leap Year? LeapYear Run This program first prompts the user to enter a year as an int value and checks if it is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 77 Example: A Simple Math Learning Tool AdditionTutor Run This example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number1 and number2 and displays a question such as “What is 7 + 9?” to the student, as shown below. After the student types the answer in the input dialog box, the program displays a message dialog box to indicate whether the answer is true or false. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 78 The & and | Operators &&: conditional AND operator &: unconditional AND operator ||: conditional OR operator |: unconditional OR operator exp1 && exp2 (1 < x) && (x < 100) (1 < x) & (x < 100) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 79 The & and | Operators If x is 1, what is x after this expression? (x > 1) & (x++ < 10) If x is 1, what is x after this expression? (1 > x) && ( 1 > x++) How about (1 == x) | (10 > x++)? (1 == x) || (10 > x++)? Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 80 Selection Statements  if Statements  switch Statements  Conditional Operators Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 81 TIP if (number % 2 == 0) even = true; else even = false; (a) Equivalent boolean even = number % 2 == 0; (b) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 82 CAUTION if (even == true) System.out.println( "It is even."); (a) Equivalent if (even) System.out.println( "It is even."); (b) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 83 Example: An Improved Math Learning Tool This example creates a program to teach a first grade child how to learn subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as “What is 9 – 2?” to the student, as shown in the figure. After the student types the answer in the input dialog box, the program displays a message dialog box to indicate whether the answer is correct, as shown in figure. SubtractionTutor Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 84 Example: Guessing Birth Date GuessBirthDate Run The program can guess your birth date. Run to see how it works. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 85 Conditional Operator, cont. (booleanExp) ? exp1 : exp2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 86 Formatting Output Use the new JDK 1.5 printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign. JDK 1.5 Feature Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 87 Frequently-Used Specifiers JDK 1.5 Feature Specifier Output Example %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" int count = 5; double amount = 45.56; System.out.printf("count is %d and amount is %f", count, amount); display count is 5 and amount is 45.560000 items Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 88 Creating Formatted Strings System.out.printf(format, item1, item2, ..., itemk) String.format(format, item1, item2, ..., itemk) String s = String.format("count is %d and amount is %f", 5, 45.56)); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 89 Operator Precedence  var++, var--  +, - (Unary plus and minus), ++var,--var  (type) Casting  ! (Not)  *, /, % (Multiplication, division, and remainder)  +, - (Binary addition and subtraction)  , >= (Comparison)  ==, !=; (Equality)  & (Unconditional AND)  ^ (Exclusive OR)  | (Unconditional OR)  && (Conditional AND) Short-circuit AND  || (Conditional OR) Short-circuit OR  =, +=, -=, *=, /=, %= (Assignment operator) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 90 while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } Loop Continuation Condition? true Statement(s) (loop body) false (count < 100)? true System.out.println("Welcome to Java!"); count++; false (A) (B) count = 0; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 91 Example: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates ten questions and reports the number of the correct answers after a student answers all ten questions. IMPORTANT NOTE: To run the program from the Run button, (1) set c:\jdk1.5.0\bin for path, and (2) install slides from the Instructor Resource Website to a directory (e.g., c:\LiangIR) . SubtractionTutorLoop Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 92 Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. SentinelValue Run IMPORTANT NOTE: To run the program from the Run button, (1) set c:\jdk1.5.0\bin for path, and (2) install slides from the Instructor Resource Website to a directory (e.g., c:\LiangIR) . Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 93 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. // data should be zero double data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero"); else System.out.println("data is not zero"); Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 94 do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); Loop Continuation Condition? true Statement(s) (loop body) false Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 95 for Loops for (initial-action; loop- continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); } Loop Continuation Condition? true Statement(s) (loop body) false (A) Action-After-Each-Iteration Initial-Action (i < 100)? true System.out.println( "Welcome to Java"); false (B) i++ i = 0 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 96 Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each- iteration in a for loop can be a list of zero or more comma- separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something } Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 97 Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion: for ( ; ; ) { // Do something } (a) Equivalent while (true) { // Do something } (b) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 98 Example: Using for Loops Problem: Write a program that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. TestSum Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 99 Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. TestMultiplicationTable Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 100 Example: Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisor Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 101 Example: Finding the Sales Amount Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. Sales Amount Commission Rate $0.01–$5,000 8 percent $5,000.01–$10,000 10 percent $10,000.01 and above 12 percent Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. FindSalesAmount Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 102 Example: Displaying a Pyramid of Numbers Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. For example, if the input integer is 12, the output is shown below. PrintPyramid Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 103 Using break and continue Examples for using the break and continue keywords:  TestBreak.java  TestContinue.java TestBreak TestContinue Run Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 104 Example: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: •For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. •Determine whether a given number is prime. •Count the prime numbers. •Print each prime number, and print 10 numbers per line. PrimeNumber Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 105 Introducing Methods A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 106 Introducing Methods, cont. • Method signature is the combination of the method name and the parameter list. • The variables defined in the method header are known as formal parameters. • When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 107 Introducing Methods, cont. • A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 108 Calling Methods Listing 5.1 Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMax Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 109 Calling Methods, cont. public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } pass the value of i pass the value of j Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 110 Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max). Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 111 Call Stacks The main method is invoked. Space required for the main method k: j: 2 i: 5 The max method is invoked. Space required for the max method result: 5 num2: 2 num1: 5 The max method is finished and the return value is sent to k. The main method is finished. Stack is empty Space required for the main method k: j: 2 i: 5 Space required for the main method k: 5 j: 2 i: 5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 112 Trace Call Stack public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Return result and assign it to k The max method is invoked. Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k:5 j: 2 i: 5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 113 Pass by Value Listing 5.2 Testing Pass by value This program demonstrates passing values to the methods. TestPassByValue Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 114 Pass by Value, cont. The main method is invoked The values of num1 and num2 are passed to n1 and n2. Executing swap does not affect num1 and num2. Space required for the main method num2: 2 num1: 1 The swap method is invoked Space required for the main method num2: 2 num1: 1 Space required for the swap method temp: n2: 2 n1: 1 The swap method is finished Space required for the main method num2: 2 num1: 1 The main method is finished Stack is empty Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 115 Overloading Methods Listing 5.3 Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } TestMethodOverloading Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 116 Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 117 Ambiguous Invocation public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 118 Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Method Signature Method body Black Box Optional arguments for Input Optional return value Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 119 Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 120 The Math Class Class constants: – PI – E Class methods: – Trigonometric Methods – Exponent Methods – Rounding Methods – min, max, abs, and random Methods Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 121 Trigonometric Methods  sin(double a)  cos(double a)  tan(double a)  acos(double a)  asin(double a)  atan(double a) Radians toRadians(90) Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 122 Exponent Methods  exp(double a) Returns e raised to the power of a.  log(double a) Returns the natural logarithm of a.  log10(double a) Returns the 10-based logarithm of a.  pow(double a, double b) Returns a raised to the power of b.  sqrt(double a) Returns the square root of a. Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 123 Rounding Methods  double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value.  double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value.  double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.  int round(float x) Return (int)Math.floor(x+0.5).  long round(double x) Return (long)Math.floor(x+0.5). Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 124 Rounding Methods Examples Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns –2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 Math.rint(2.1) returns 2.0 Math.rint(2.0) returns 2.0 Math.rint(-2.0) returns –2.0 Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 Math.rint(-2.5) returns -2.0 Math.round(2.6f) returns 3 Math.round(2.0) returns 2 Math.round(-2.0f) returns -2 Math.round(-2.6) returns -3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 125 min, max, and abs  max(a, b)and min(a, b) Returns the maximum or minimum of two parameters.  abs(a) Returns the absolute value of the parameter.  random() Returns a random double value in the range [0.0, 1.0). Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 126 The random Method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: (int)(Math.random() * 10) Returns a random integer between 0 and 9. 50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99. In general, a + Math.random() * b Returns a random number between a and a + b, excluding a + b. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 127 Stepwise Refinement (Optional) The concept of method abstraction can be applied to the process of developing programs. When writing a large program, you can use the “divide and conquer” strategy, also known as stepwise refinement, to decompose it into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. PrintCalendar Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 128 PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. Run Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 129 Design Diagram printCalendar (main) readInput printMonth getStartDay printMonthTitle printMonthBody getTotalNumOfDays getNumOfDaysInMonth getMonthName isLeapYear Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 130 Implementation: Top-Down A Skeleton for printCalendar Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. Implement the main method first and then use a stub for the printMonth method. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this: Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 131 Implementation: Bottom-Up Bottom-up approach is to implement one method in the structure chart at a time from the bottom to the top. For each method implemented, write a test program to test it. Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 132 Package There are three reasons for using packages: 1. To avoid naming conflicts. When you develop reusable classes to be shared by other programmers, naming conflicts often occur. To prevent this, put your classes into packages so that they can be referenced through package names. 2. To distribute software conveniently. Packages group related classes so that they can be easily distributed. 3. To protect classes. Packages provide protection so that the protected members of the classes are accessible to the classes in the same package, but not to the external classes. Optional Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 133 Package-Naming Conventions Packages are hierarchical, and you can have packages within packages. For example, java.lang.Math indicates that Math is a class in the package lang and that lang is a package in the package java. Levels of nesting can be used to ensure the uniqueness of package names. Choosing a unique name is important because your package may be used on the Internet by other programs. Java designers recommend that you use your Internet domain name in reverse order as a package prefix. Since Internet domain names are unique, this prevents naming conflicts. Suppose you want to create a package named mypackage on a host machine with the Internet domain name prenhall.com. To follow the naming convention, you would name the entire package com.prenhall.mypackage. By convention, package names are all in lowercase. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 134 Package Directories Java expects one-to-one mapping of the package name and the file system directory structure. For the package named com.prenhall.mypackage, you must create a directory, as shown in the figure. In other words, a package is actually a directory that contains the bytecode of the classes. com.prenhall.mypackage The com directory does not have to be the root directory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 135 Setting classpath Environment The com directory does not have to be the root directory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Suppose the com directory is under c:\book. The following line adds c:\book into the classpath: classpath=.;c:\book; The period (.) indicating the current directory is always in classpath. The directory c:\book is in classpath so that you can use the package com.prenhall.mypackage in the program. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 136 Putting Classes into Packages Every class in Java belongs to a package. The class is added to the package when it is compiled. All the classes that you have used so far in this book were placed in the current directory (a default package) when the Java source programs were compiled. To put a class in a specific package, you need to add the following line as the first noncomment and nonblank statement in the program: package packagename; Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 137 Listing 5.8 Putting Classes into Packages Problem This example creates a class named Format and places it in the package com.prenhall.mypackage. The Format class contains the format(number, numOfDecimalDigits) method that returns a new number with the specified number of digits after the decimal point. For example, format(10.3422345, 2) returns 10.34, and format(-0.343434, 3) returns –0.343. Solution 1. Create Format.java as follows and save it into c:\book\com\prenhall\mypackage. // Format.java: Format number. package com.prenhall.mypackage; public class Format { public static double format( double number, int numOfDecimalDigits) { return Math.round(number * Math.pow(10, numOfDecimalDigits)) / Math.pow(10, numOfDecimalDigits); } } 2. Compile Format.java. Make sure Format.class is in c:\book\com\prenhall\mypackage. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 138 Using Classes from Packages There are two ways to use classes from a package. • One way is to use the fully qualified name of the class. For example, the fully qualified name for JOptionPane is javax.swing.JOptionPane. For Format in the preceding example, it is com.prenhall.mypackage.Format. This is convenient if the class is used a few times in the program. • The other way is to use the import statement. For example, to import all the classes in the javax.swing package, you can use import javax.swing.*; An import that uses a * is called an import on demand declaration. You can also import a specific class. For example, this statement imports javax.swing.JOptionPane: import javax.swing.JOptionPane; The information for the classes in an imported package is not read in at compile time or runtime unless the class is used in the program. The import statement simply tells the compiler where to locate the classes. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 139 Listing 5.9 Using Packages Problem This example shows a program that uses the Format class in the com.prenhall.mypackage.mypackage package. Solution 1. Create TestFormatClass.java as follows and save it into c:\book. The following code gives the solution to the problem. // TestFormatClass.java: Demonstrate using the Format class import com.prenhall.mypackage.Format; public class TestFormatClass { /** Main method */ public static void main(String[] args) { System.out.println(Format.format(10.3422345, 2)); System.out.println(Format.format(-0.343434, 3)); } }

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

  • pdfadvanced_programminglanguage_nguyencaodat_c1_0122_1811633.pdf
Tài liệu liên quan