Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 2 Primitive Data Types and Operations Prerequisites for Part I Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Control Statements 事实不可扭曲,意见大可自由 Chapter 4 Methods —— C.P.Scott Chapter 5 Arrays Liang, Introduction to Java Programming,revised by Dai-kaiyu 1 Objectives To write Java programs to perform simple calculations (§2.2). To use identifiers to name variables, constants, methods, and classes (§2.3). To use variables to store data (§2.4-2.5). To program with assignment statements and assignment expressions (§2.5). To use constants to store permanent data (§2.6). To declare Java primitive data types: byte, short, int, long, float, double, char, and boolean (§2.7 – 2.10). To use Java operators to write expressions (§2.7 – 2.10). To know the rules governing operand evaluation order, operator precedence, and operator associativity (§2.11 – 2.12). To represent a string using the String type. (§2.13) To obtain input using the JOptionPane input dialog boxes (§2.14). To obtain input from console (§2.16 Optional). To format output using JDK 1.5 printf (§2.17). To become familiar with Java documentation, programming style, and naming conventions (§2.18). To distinguish syntax errors, runtime errors, and logic errors (§2.19). 2 Liang, Introduction to Java Programming,revised by Dai-kaiyu To debug logic errors (§2.20). Introducing Programming with an Example Example 2.1 Computing the Area of a Circle Program = Algorithm + Data structure ComputeArea Run Liang, Introduction to Java Programming,revised by Dai-kaiyu 3 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; allocate memory for radius radius no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 4 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; memory radius no value area no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; allocate memory for area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 5 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; assign 20 to radius radius area 20 no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 6 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; memory radius area 20 1256.636 // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; compute area and assign it to variable area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 7 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; memory radius area 20 1256.636 // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; print a message to the console // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } A string constant should not cross lines Liang, Introduction to Java Programming,revised by Dai-kaiyu 8 Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved word. An identifier can be of any length. Are used for naming variables, constants, methods, classes, and packages Liang, Introduction to Java Programming,revised by Dai-kaiyu 9 Liang, Introduction to Java Programming,revised by Dai-kaiyu 10 Memory Concepts Variables Every variable has a name, a type, a size and a value Name corresponds to location in memory When new value is placed into a variable, replaces (and destroys) previous value Reading variables from memory does not change them Liang, Introduction to Java Programming,revised by Dai-kaiyu 11 2.6 Memory Concepts Visual Representation Sum = 0; number1 = 1; number2 = 2; number1 sum 1 0 number2 2 Sum = number1 + number2; after execution of statement number1 sum 3 Liang, Introduction to Java Programming,revised by Dai-kaiyu number2 1 2 12 Variables Used to store data in a program // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is " + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); Liang, Introduction to Java Programming,revised by Dai-kaiyu 13 Declaring Variables Giving the name and the data type of variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; Liang, Introduction to Java Programming,revised by Dai-kaiyu 14 Java data types Data type is the classification of forms of information Data type is declared using keywords Java is strongly typed Liang, Introduction to Java Programming,revised by Dai-kaiyu 15 Assignment Statements Give a value to the declared variable x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; Liang, Introduction to Java Programming,revised by Dai-kaiyu 16 Assignment Expressions Expression: a computation involving values, variables, and operators that evaluates to a value. X = 5 * ( 3 / 2 ) + 3 * 2; Assignment expressions: i = j = k = 1; Liang, Introduction to Java Programming,revised by Dai-kaiyu 17 Declaring and Initializing in One Step int x = 1; double d = 1.4; float f = 1.4; Is this statement correct? A variable in method must be assigned a value before it can be used Liang, Introduction to Java Programming,revised by Dai-kaiyu 18 Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3; Liang, Introduction to Java Programming,revised by Dai-kaiyu 19 Numerical Data Types byte 8 bits short 16 bits type int 32 bits long 64 bits size range byte 1byte -128 ~ 127 short 2bytes -215 ~ 215-1 4bytes -231 ~ 231-1 8bytes -263 ~ 263-1 float 32 bits int double 64 bits long Liang, Introduction to Java Programming,revised by Dai-kaiyu 20 Operators +, -, *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division) Liang, Introduction to Java Programming,revised by Dai-kaiyu 21 Remainder Operator determine whether a number is even or odd using %. Suppose you know January 1, 2005 is Saturday, you can find that the day for February 1, 2005 is Tuesday using the following expression: Saturday is the 6th day in a week A week has 7 days (6 + 31) % 7 is 2 The 2nd day in a week is Tuesday January has 31 days Liang, Introduction to Java Programming,revised by Dai-kaiyu 22 NOTE Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. Show case FloatIsNotPrecise.java Liang, Introduction to Java Programming,revised by Dai-kaiyu 23 Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5.0; A compilation error would occur if the literal were too large for the variable to hold. byte b = 1000 Wrong Liang, Introduction to Java Programming,revised by Dai-kaiyu 24 Number Literals An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231– 1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. long j = 10; Is this statement correct? correct By default, a floating-point literal is treated as a double type value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2 Liang, Introduction to Java Programming,revised by Dai-kaiyu 25 Arithmetic Expressions 3 4 x 10( y 5)( a b c) 4 9 x 9( ) 5 x x y 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,revised by Dai-kaiyu 26 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,revised by Dai-kaiyu 27 Increment and Decrement Operators Operator ++var var++ --var var-- Name preincrement and evaluates postincrement original value predecrement and evaluates postdecrement value Description The expression (++var) increments var by 1 to the new value in var after the increment. The expression (var++) evaluates to the in var and increments var by 1. The expression (--var) decrements var by 1 to the new value in var after the decrement. The expression (var--) evaluates to the original in var and decrements var by 1. Liang, Introduction to Java Programming,revised by Dai-kaiyu 28 Increment and Decrement Operators, cont. int i = 10; int newNum = 10 * i++; int i = 10; int newNum = 10 * (++i); Same effect as int newNum = 10 * i; i = i + 1; Same effect as i = i + 1; int newNum = 10 * i; Liang, Introduction to Java Programming,revised by Dai-kaiyu 29 补充了解 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,revised by Dai-kaiyu 30 Numeric Type Conversion Consider the following statements: long k = i * 3 + 4; double d = i * 3.1 + k / 2; Liang, Introduction to Java Programming,revised by Dai-kaiyu 31 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,revised by Dai-kaiyu 32 Conversion Rules Datatype of oprand1 Datatype of oprand2 After convertion byte、short、char int byte、short、char、 int long long byte、short、char、 int、long float float byte、short、char、 int、long、float double double Liang, Introduction to Java Programming,revised by Dai-kaiyu int 33 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; Liang, Introduction to Java Programming,revised by Dai-kaiyu 34 Type Casting For a variable of type int , explicit casting must be used int i = 1; wrong byte b = i ; For a literal of type integer, if in the persission range of short or byte. Explicit casting is not needed byte i = 1; Liang, Introduction to Java Programming,revised by Dai-kaiyu 35 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) Four hexadecimal digits. char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. the following statements display character b. char ch = 'a'; System.out.println(++ch); 36 Liang, Introduction to Java Programming,revised by Dai-kaiyu Unicode Format Encoding: convert a character to its binary representation Java characters use Unicode, a 16-bit encoding scheme Unicode can represent 65,536 characters 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,revised by Dai-kaiyu 37 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 Show case Welcome4.java Liang, Introduction to Java Programming,revised by Dai-kaiyu 38 Appendix B: ASCII Character Set ASCII is a 7-bits encoding scheme ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming,revised by Dai-kaiyu 39 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang, Introduction to Java Programming,revised by Dai-kaiyu 40 Casting between char and Numeric Types int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97; char letter = ‘A’; System.out.println( letter+10); System.out.println((char)(letter+10)); Integerchar :lower sixteen bits are used Floating-pointchar :first cast into an int Char numeric type : Unicode is used Liang, Introduction to Java Programming,revised by Dai-kaiyu 41 The boolean Type and Operators six comparison operators (relational operators) Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to The result of the comparison is a Boolean value: true or false(can’t using 1 or 0). boolean b = (1 > 2); Liang, Introduction to Java Programming,revised by Dai-kaiyu 42 Boolean Operators Also called logic operators Operator Name ! not && and || or ^ exclusive or Liang, Introduction to Java Programming,revised by Dai-kaiyu 43 Truth Table for Operator ! p !p true false !(1 > 2) is true, because (1 > 2) is false. false true !(1 > 0) is false, because (1 > 0) is true. Example Liang, Introduction to Java Programming,revised by Dai-kaiyu 44 Truth Table for Operator && p1 p2 p1 && p2 false false false false true false true false false true true true Example (3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true. (3 > 2) && (5 > 5) is false, because (5 > 5) is false. Liang, Introduction to Java Programming,revised by Dai-kaiyu 45 Truth Table for Operator || p1 p2 p1 || p2 false false false false true true true false true true true true Example (2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false. (3 > 2) || (5 > 5) is true, because (3 > 2) is true. Liang, Introduction to Java Programming,revised by Dai-kaiyu 46 Truth Table for Operator ^ p1 p2 p1 ^ p2 false false false false true true true false true true true false Example (2 > 3) ^ (5 > 1) is true, because (2 > 3) is false and (5 > 1) is true. (3 > 2) ^ (5 > 1) is false, because both (3 > 2) and (5 > 1) are true. One of p1 and p2 is true, but not both Liang, Introduction to Java Programming,revised by Dai-kaiyu 47 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,revised by Dai-kaiyu 48 Leap Year? A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); Liang, Introduction to Java Programming,revised by Dai-kaiyu 49 The & and | Operators &&: conditional AND operator (shortcut) &: unconditional AND operator ||: conditional OR operator (shortcut) |: unconditional OR operator exp1 && exp2 (1 < x) && (x < 100) (1 < x) & (x < 100) Liang, Introduction to Java Programming,revised by Dai-kaiyu 50 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,revised by Dai-kaiyu 51 Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1? The expression in the parentheses is evaluated first All binary operators except assignment operators are left-associative. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) Liang, Introduction to Java Programming,revised by Dai-kaiyu 52 Operator Precedence var++, var-+, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) . Preceeds casting & (Unconditional AND) ^ (Exclusive OR) | (Unconditional OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) Liang, Introduction to Java Programming,revised by Dai-kaiyu 53 Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: 3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 3 + 16 > 5 * 7 – 1 (1) inside parentheses first (2) multiplication (3) multiplication 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false (4) addition (5) subtraction (6) greater than Liang, Introduction to Java Programming,revised by Dai-kaiyu 54 Operand Evaluation Order Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. int a = 0; int x = a + (++a); x becomes 1 int a = 0; int x = ++a + a; x becomes 2 Liang, Introduction to Java Programming,revised by Dai-kaiyu 55 Rule of Evaluating an Expression · Rule 1: Evaluate whatever subexpressions you can possibly evaluate from left to right. · Rule 2: The operators are applied according to their precedence, as shown in Table 2.11. · Rule 3: The associativity rule applies for two operators next to each other with the same precedence. Liang, Introduction to Java Programming,revised by Dai-kaiyu 56 Rule of Evaluating an Expression · Applying the rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: 3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 16 > 5 * (4 + 3) - 1 (1) 4 * 4 is the first subexpression that can be evaluated from left. (2) 3 + 16 is evaluated now. 19 > 5 * (4 + 3) - 1 19 > 5 * 7 - 1 (3) 4 + 3 is now the leftmost subexpression that should be evaluated. (4) 5 * 7 is evaluated now. 19 > 35 – 1 19 > 34 false (5) 35 – 1 is evaluated now. (6) 19 > 34 is evaluated now. Liang, Introduction to Java Programming,revised by Dai-kaiyu 57 The String Type represent a string of characters, use the data type called String. String message = "Welcome to Java"; String is actually a predefined class in the Java library 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. Liang, Introduction to Java Programming,revised by Dai-kaiyu 58 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,revised by Dai-kaiyu 59 String Concatenation + operator Addition String concatenation int y=5; System.out.println("y+2="+y+2); System.out.println(y+2+"y+2="); System.out.println("y+2="+(y+2)); Show case Concatination.java Liang, Introduction to Java Programming,revised by Dai-kaiyu 60 Obtaining Input Two common ways of obtaining input. 1. Using JOptionPane input dialogs (§2.14) 2. Using the JDK 1.5 Scanner class (Supplement T) Liang, Introduction to Java Programming,revised by Dai-kaiyu 61 Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE)); Liang, Introduction to Java Programming,revised by Dai-kaiyu 62 Message dialog type Icon Description JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error to the user. JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational message to the user. The user can simply dismiss the dialog. JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a potential problem. JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button. JOptionPane.PLAIN_MESSAGE JOptionPane no icon Displays a dialog that simply contains a message, with no icon. constants for message dialogs. Liang, Introduction to Java Programming,revised by Dai-kaiyu 63 Two Ways to Invoke the Method There are several ways to use the showInputDialog method. For 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. JOptionPane. showInputDialog(x); where x is a string for the prompting message. Liang, Introduction to Java Programming,revised by Dai-kaiyu 64 Converting Strings to Integers 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,revised by Dai-kaiyu 65 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,revised by Dai-kaiyu 66 Detailed case study: Adding Integers Upcoming program Use input dialogs to input two values from user Use message dialog to display sum of the two values Liang, Introduction to Java Programming,revised by Dai-kaiyu 67 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Fig. 2.9: Addition.java // An addition program. // Java extension packages import javax.swing.JOptionPane; // import class JOptionPane public class Addition { Declare variables: name and data type. // main method begins execution of Java application public static void main( String args[] ) { Input by first integer String firstNumber; // first string entered user String secondNumber; // second string entered by user firstNumber. int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 as a String, assign to // read in first number from user as a String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a String secondNumber = Convert strings JOptionPane.showInputDialog( "Enter second integer" ); to integers. Add, place result in sum. // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // add the numbers sum = number1 + number2; Liang, Introduction to Java Programming,revised by Dai-kaiyu 68 33 // display the results 34 JOptionPane.showMessageDialog( 35 null, "The sum is " + sum, "Results", 36 JOptionPane.PLAIN_MESSAGE ); 37 38 System.exit( 0 ); // terminate application 39 40 } // end method main 41 42 } // end class Addition Liang, Introduction to Java Programming,revised by Dai-kaiyu 69 Detailed case study: Adding 5 Integers import javax.swing.JOptionPane; Location of JOptionPane for use in the program 7 public class Addition { Begins public class Addition Recall that file name must be Addition.java Lines 10-11: main 12 13 String firstNumber; String secondNumber; // first string entered by user // second string entered by user Declaration firstNumber and secondNumber are variables Liang, Introduction to Java Programming,revised by Dai-kaiyu 70 Detailed case study: Adding 12 13 String firstNumber; String secondNumber; Integers // first string entered by user // second string entered by user Variables Location in memory that stores a value • Declare with name and data type before use firstNumber and secondNumber are of data type String (package java.lang) • Hold strings Variable name: any valid identifier Declarations end with semicolons ; String firstNumber, secondNumber; • Can declare multiple variables of the same type at a time • Use comma separated list Can add comments to describe purpose of variables Liang, Introduction to Java Programming,revised by Dai-kaiyu 71 Good Practice •meaningful varible name, self-documenting •String firstNumber; •String secondNumber; •begin with lowercase letter Liang, Introduction to Java Programming,revised by Dai-kaiyu 72 Detailed case study: Adding 14 15 16 int number1; int number2; int sum; Integers // first number to add // second number to add // sum of number1 and number2 Declares variables number1, number2, and sum of type int int holds integer values : i.e., 0, -4, 97 Data types float and double can hold decimal numbers Data type char can hold a single character: i.e., x, $, \n, 7 • Single letter, single digit, single special character and escape sequences. Primitive data types(Built in data types) • Boolean, char, byte, short, int, long, float, double Liang, Introduction to Java Programming,revised by Dai-kaiyu 73 Detailed case study: Adding 19 20 Integers firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); Reads String from the user, representing the first number to be added Method JOptionPane.showInputDialog displays the following: Message called a prompt - directs user to perform an action Argument appears as prompt text If wrong type of data entered (non-integer) or click Cancel, error occurs (fault tolerant) Liang, Introduction to Java Programming,revised by Dai-kaiyu 74 Detailed case study: Adding 19 20 Integers firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); Result of call to showInputDialog given to firstNumber using assignment operator = Assignment statement = binary operator - takes two operands • Expression on right evaluated and assigned to variable on left Read as: firstNumber gets value of JOptionPane.showInputDialog( "Enter first integer" ) Liang, Introduction to Java Programming,revised by Dai-kaiyu 75 Detailed case study: Adding 23 24 Integers secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); Similar to previous statement Assigns variable secondNumber to second integer input 27 28 number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); Method Integer.parseInt Converts String argument into an integer (type int) • Class Integer in java.lang Integer returned by Integer.parseInt is assigned to variable number1 (line 27) • Remember that number1 was declared as type int Line 28 similar Liang, Introduction to Java Programming,revised by Dai-kaiyu 76 Detailed case study: Adding 31 Integers sum = number1 + number2; Assignment statement Calculates sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 Good Practice : number1 and number2 are operands Space on either side of binary operator(make it stand out) Liang, Introduction to Java Programming,revised by Dai-kaiyu 77 Detailed case study: Adding 34 35 36 Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); Use showMessageDialog to display results "The sum is " + sum Uses the operator + to "add" the string literal "The sum is" and sum Concatenation of a String and another data type • Results in a new string • Automatic conversion of integer to string. If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117" Note the space in "The sum is " Liang, Introduction to Java Programming,revised by Dai-kaiyu 78 Detailed case study: Adding 34 35 36 Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); Different version of showMessageDialog Requires four arguments (instead of two as before) First argument: null for now Second: string to display Third: string in title bar Fourth: type of message dialog with icon • Line 36 no icon: JOptionPane.PLAIN_MESSAGE Liang, Introduction to Java Programming,revised by Dai-kaiyu 79 Example 2.2 Entering Input from Dialog Boxes This program first prompts the user to enter a year as an int value and checks if it is a leap year, it then prompts you to enter a double value and checks if it is positive. 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) InputDialogDemo Liang, Introduction to Java Programming,revised by Dai-kaiyu Run 80 Example 2.3 Computing Loan Payments This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment. loanAmount monthlyInterestRate 1 1 numOfYears12 (1 monthlyInterestRate) ComputeLoan Run Liang, Introduction to Java Programming,revised by Dai-kaiyu 81 Example 2.4 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 Liang, Introduction to Java Programming,revised by Dai-kaiyu Run 82 Trace ComputeChange Suppose amount is 11.56 int remainingAmount = (int)(amount * 100); remainingAmount // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; 1156 remainingAmount initialized // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; Liang, Introduction to Java Programming,revised by Dai-kaiyu 83 Trace ComputeChange Suppose amount is 11.56 int remainingAmount = (int)(amount * 100); remainingAmount // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; numberOfOneDollars // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; 1156 11 numberOfOneDollars assigned // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; Liang, Introduction to Java Programming,revised by Dai-kaiyu 84 Trace ComputeChange Suppose amount is 11.56 int remainingAmount = (int)(amount * 100); remainingAmount 56 // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; numberOfOneDollars 11 // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; remainingAmount updated // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; Liang, Introduction to Java Programming,revised by Dai-kaiyu 85 Trace ComputeChange Suppose amount is 11.56 int remainingAmount = (int)(amount * 100); remainingAmount 56 // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; numberOfOneDollars 11 // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; numberOfOneQuarters 2 // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; numberOfOneQuarters assigned // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; Liang, Introduction to Java Programming,revised by Dai-kaiyu 86 Trace ComputeChange Suppose amount is 11.56 int remainingAmount = (int)(amount * 100); remainingAmount 6 // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; numberOfOneDollars 11 // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; numberOfQuarters 2 // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; remainingAmount updated // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; Liang, Introduction to Java Programming,revised by Dai-kaiyu 87 Example 2.5 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 Liang, Introduction to Java Programming,revised by Dai-kaiyu Run 88 Optional Supplement T 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 Liang, Introduction to Java Programming,revised by Dai-kaiyu Run 89 JDK 1.5 Feature Formatting Output Use the new JDK 1.5 printf statement. System.out.printf(format, item); 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. Liang, Introduction to Java Programming,revised by Dai-kaiyu 90 JDK 1.5 Feature Frequently-Used Specifiers Table 2.13 for detailed usage examples 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; items 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 Liang, Introduction to Java Programming,revised by Dai-kaiyu 91 Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles Coding conventions Liang, Introduction to Java Programming,revised by Dai-kaiyu 92 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. Javadoc brief intro Liang, Introduction to Java Programming,revised by Dai-kaiyu 93 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,revised by Dai-kaiyu 94 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,revised by Dai-kaiyu 95 Proper Indentation and Spacing Indentation Indent two spaces. Spacing Use blank line to separate segments of the code. Liang, Introduction to Java Programming,revised by Dai-kaiyu 96 Block Styles Use end-of-line style for braces. Next-line style 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"); } } Liang, Introduction to Java Programming,revised by Dai-kaiyu End-of-line style 97 Programming Errors Syntax Errors Detected by the compiler Runtime Errors Causes the program to abort Logic Errors Produces incorrect result Liang, Introduction to Java Programming,revised by Dai-kaiyu 98 Syntax Errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); Not declared } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 99 Runtime Errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } Devided by zero } Liang, Introduction to Java Programming,revised by Dai-kaiyu 100 Logic Errors public class ShowLogicErrors { // Determine if a number is between 1 and 100 inclusively public static void main(String[] args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); // Display the result System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 > number) && (number < 100))); System.exit(0); Wrong expression } } Liang, Introduction to Java Programming,revised by Dai-kaiyu 101 Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. Debugger is a program that facilitates debugging. You can use a debugger to Execute a single statement at a time. Trace into or stepping over a method. Set breakpoints. Display variables. Display call stack. Modify variables. Liang, Introduction to Java Programming,revised by Dai-kaiyu 102 JBuilder Optional Debugging in JBuilder The debugger utility is integrated in JBuilder. You can pinpoint bugs in your program with the help of the JBuilder debugger without leaving the IDE. The JBuilder debugger enables you to set breakpoints and execute programs line by line. As your program executes, you can watch the values stored in variables, observe which methods are being called, and know what events have occurred in the program. Liang, Introduction to Java Programming,revised by Dai-kaiyu 103 JBuilder Optional Setting Breakpoints A breakpoint is a stop sign placed on a line of source code that tells the debugger to pause when this line is encountered. Using the breakpoint, you can quickly move over the sections you know work correctly and concentrate on the sections causing problems. Liang, Introduction to Java Programming,revised by Dai-kaiyu 104 JBuilder Optional Setting Breakpoints, cont. Cutter area As you debug your program, you can set as many breakpoints as you want, and can remove breakpoints at any time during debugging. The project retains the breakpoints you have set when you exit the project. The breakpoints are restored when you reopen it. Breakpoint Liang, Introduction to Java Programming,revised by Dai-kaiyu 105 JBuilder Optional Starting the debugger 1. Set breakpoints. 2. Choose the program (e.g., ShowCurrentTime.java in the project pane, and right-click the mouse button to display the context menu. Click Debug Using Defaults in the context menu to start debugging. Liang, Introduction to Java Programming,revised by Dai-kaiyu 106 JBuilder Optional Console View Console view displays output and errors. You can also enter input from the console view. Console view Liang, Introduction to Java Programming,revised by Dai-kaiyu 107 JBuilder Optional Stack View Stack view displays the methods and local variables in the call stack. Call stacks Liang, Introduction to Java Programming,revised by Dai-kaiyu 108 JBuilder Optional Watch View You can add variables to the watch view. Watch view displays the contents of the variables in the watch view. Data watches Liang, Introduction to Java Programming,revised by Dai-kaiyu 109 JBuilder Optional Adding Variables to Watch View There are several ways to add variables to the watch view. A simple way is to highlight the variable and then right-click the mouse to display the context menu. Choose Add Watch in the context menu to add the variable to the watch view. Liang, Introduction to Java Programming,revised by Dai-kaiyu 110 JBuilder Optional Controlling Program Execution The program pauses at the first breakpoint line encountered. This line, called the current execution point, is highlighted and has a green arrow to the left. The execution point marks the next line of source code to be executed by the debugger. When the program pauses at the execution point, you can issue debugging commands to control the execution of the program. You also can inspect or modify the values of variables in the program. When JBuilder is in the debugging mode, the Run menu contains the debugging commands. Most of the commands also appear in the toolbar under the message pane. The toolbar contains additional commands that are not in the Run menu. Here are the commands for controlling program execution: Liang, Introduction to Java Programming,revised by Dai-kaiyu 111 JBuilder Optional Debugger Commands in the Toolbar Reset program Resume program Pause program Step over Step Step into out Liang, Introduction to Java Programming,revised by Dai-kaiyu 112 JBuilder Optional Debugger Commands in the Menu Liang, Introduction to Java Programming,revised by Dai-kaiyu 113 JBuilder Optional Debugger Commands Step Over executes a single statement. If the statement contains a call to a method, the entire method is executed without stepping through it. Step Into executes a single statement or steps into a method. Step Out executes all the statements in the current method and returns to its caller. Run to Cursor runs the program, starting from the current execution point, and pauses and places the execution point on the line of code containing the cursor, or at a breakpoint. Run to End of Method runs the program until it reaches the end of the current method or a breakpoint. Resume Program continues the current debugging session or restarts one that has finished or been reset. Reset Program ends the current program and releases it from memory. Use Reset to restart an application from the beginning, as when you make a change to the code and want to run again from the beginning, or if variables or data structures become corrupted with unwanted values. This command terminates debugging and returns to the normal editing session. Show Execution Point positions the cursor at the execution point in the content pane. Liang, Introduction to Java Programming,revised by Dai-kaiyu 114 JBuilder Optional Tracing Execution You may trace the program line by line and see the contents of the variables in the stack view. This is most convenient. Liang, Introduction to Java Programming,revised by Dai-kaiyu 115