Upload
ugurcan-uzer
View
653
Download
3
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
1
Chapter 3 Selections
2
Motivations
If you assigned a negative value for radius in Listing 2.1, ComputeArea.java, the program would print an invalid result. If the radius is negative, you don't want the program to compute the area. How can you deal with this situation?
3
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);
4
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
5
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
6
Truth Table for Operator !
p !p
true false
false true
Example
!(1 > 2) is true, because (1 > 2) is false.
!(1 > 0) is false, because (1 > 0) is true.
If p is true, !p is falseIf p is false, !p is true
7
Truth Table for Operator && (AND)
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.
Both p1 and p2 have to be true for p1 && p2 to be true, otherwise p1 && p2 is false
8
Truth Table for Operator || (OR)
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 t rue, because (3 > 2) is true.
Both p1 and p2 have to be false for p1 || p2 to be false, otherwise p1 || p2 is true
9
Truth Table for Operator ^ (exclusive-OR)
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.
Both p1 and p2 have to be true or both have to be false for p1 ^ p2 to be false, otherwise p1 ^ p2 is true
10
Examples
System.out.println("Is " + number + " divisible by 2 and 3? " + ((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
If both number divided by 2 and number divided by 3 have a remainder of 0 then true will be displayed, otherwise false will be displayed
If either number divided by 2 or number divided by 3 have a remainder of 0 then true will be displayed, otherwise false will be displayed
If either number divided by 2 or number divided by 3 have a remainder of 0 but not both then true will be displayed, otherwise false will be displayed
11
Problem: Determining Leap Year?
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)
12
LeapYear.javaimport java.util.Scanner; public class LeapYear { public static void main(String args[]) { // Create a Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a year: "); int year = input.nextInt(); // Check if the year is a leap year boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); // Display the result in a message dialog box System.out.println(year + " is a leap year? " + isLeapYear); } }
13
Problem: A Simple Math Learning Tool
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. After the student types the answer, the program displays a message to indicate whether the answer is true or false.
14
AdditionQuiz.javaimport java.util.Scanner;
public class AdditionQuiz {
public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() * 7 % 10);
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print( "What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
System.out.println( number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));
}
}
15
Selection Statements
if Statements
switch Statements
Conditional Operators
16
Simple if Statements
if (booleanExpression) { statement(s);}
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area"
+ " for the circle of radius "
+ radius + " is " + area);
}
Boolean Expression
true
Statement(s)
false (radius >= 0)
true
area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area);
false
(A) (B)
17
Note
if ((i > 0) && (i < 10)) { System.out.println("i is an " +
+ "integer between 0 and 10"); }
(a)
Equivalent
(b)
if ((i > 0) && (i < 10)) System.out.println("i is an " +
+ "integer between 0 and 10");
Outer parentheses required Braces can be omitted if the block contains a single statement
18
CautionAdding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
Wrong
19
The if...else Statement
if (booleanExpression) { statement(s)-for-the-true-case;}else { statement(s)-for-the-false-case;}
Boolean Expression
false true
Statement(s) for the false case Statement(s) for the true case
20
if...else Example
if (radius >= 0) { area = radius * radius * 3.14159;
System.out.println("The area for the “ + “circle of radius " + radius + " is " + area);}else { System.out.println("Negative input");}
21
Multiple Alternative if Statements
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
Equivalent
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
22
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is false
animation
23
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is false
animation
24
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 The condition is true
animation
25
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 grade is C
animation
26
Trace if-else statement
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 Exit the if statement
animation
27
NoteThe else clause matches the most recent if clause in the same block.
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
(a)
Equivalent
(b)
int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");
28
Note, cont.Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
29
TIP
if (number % 2 == 0) even = true; else even = false;
(a)
Equivalent boolean even = number % 2 == 0;
(b)
30
CAUTION
if (even == true) System.out.println( "It is even.");
(a)
Equivalent if (even) System.out.println( "It is even.");
(b)
31
Problem: 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. 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.
32
SubtractionQuiz.javaimport java.util.Scanner; public class SubtractionQuiz { public static void main(String[] args) { // 1. Generate two random single-digit integers int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); // 2. If number1 < number2, swap number1 with number2 if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } // 3. Prompt the student to answer “what is number1 – number2?” System.out.print ("What is " + number1 + " - " + number2 + "? "); Scanner input = new Scanner(System.in); int answer = input.nextInt(); // 4. Grade the answer and display the result if (number1 - number2 == answer) System.out.println("You are correct!"); else System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should be " +
(number1 - number2)); } }
33
Problem: Lottery Randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule:
• If the user input matches the lottery in exact order, the award is $10,000.
• If the user input matches the lottery, the award is $3,000.
• If one digit in the user input matches a digit in the lottery, the award is $1,000.
34
Lottery.javaimport java.util.Scanner; public class Lottery { public static void main(String[] args) { // Generate a lottery int lottery = (int)(Math.random() * 100); // Prompt the user to enter a guess Scanner input = new Scanner(System.in); System.out.print("Enter your lottery pick: "); int guess = input.nextInt(); // Check the guess if (guess == lottery) System.out.println("Exact match: you win $10,000"); else if (guess % 10 == lottery / 10 && guess / 10 == lottery % 10) System.out.println("Match all digits: you win $3,000"); else if (guess % 10 == lottery / 10 || guess % 10 == lottery % 10 || guess / 10 ==
lottery / 10 || guess / 10 == lottery % 10) System.out.println("Match one digit: you win $1,000"); else System.out.println("Sorry, no match"); } }
35
Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows:
BMI Interpretation below 16 serious underweight
16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight
36
ComputeBMI.javaimport java.util.Scanner; public class ComputeBMI { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble(); // Prompt the user to enter height in inches System.out.print("Enter height in inches: "); double height = input.nextDouble(); final double KILOGRAMS_PER_POUND = 0.45359237; // Constant final double METERS_PER_INCH = 0.0254; // Constant // Compute BMI double bmi = weight * KILOGRAMS_PER_POUND / ((height * METERS_PER_INCH) * (height *
METERS_PER_INCH)); // Display result System.out.println("Your BMI is " + bmi); if (bmi < 16) System.out.println("You are seriously under weight"); else if (bmi < 18) System.out.println("You are under weight"); else if (bmi < 24) System.out.println("You are normal weight"); else if (bmi < 29) System.out.println("You are over weight"); else if (bmi < 35) System.out.println("You are seriously over weight"); else System.out.println("You are gravely over weight"); } }
37
Problem: Computing TaxesThe US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.1.
38
Problem: Computing Taxes, cont.if (status == 0) { // Compute tax for single filers}else if (status == 1) { // Compute tax for married file jointly}else if (status == 2) { // Compute tax for married file separately}else if (status == 3) { // Compute tax for head of household}else { // Display wrong status}
39
ComputeTax.javaimport java.util.Scanner; public class ComputeTax { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter filing status System.out.print( "(0-single filer, 1-married jointly,\n" + "2-married separately, 3-head of household)\n" + "Enter the filing status: "); int status = input.nextInt(); // Prompt the user to enter taxable income System.out.print("Enter the taxable income: "); double income = input.nextDouble();
40
ComputeTax.java // Compute tax double tax = 0; if (status == 0) { // Compute tax for single filers if (income <= 6000) tax = income * 0.10; else if (income <= 27950) tax = 6000 * 0.10 + (income - 6000) * 0.15; else if (income <= 67700) tax = 6000 * 0.10 + (27950 - 6000) * 0.15 + (income - 27950) * 0.27; else if (income <= 141250) tax = 6000 * 0.10 + (27950 - 6000) * 0.15 + (67700 - 27950) * 0.27 + (income - 67700) * 0.30; else if (income <= 307050) tax = 6000 * 0.10 + (27950 - 6000) * 0.15 + (67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 + (income - 141250) * 0.35; else tax = 6000 * 0.10 + (27950 - 6000) * 0.15 + (67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 + (307050 - 141250) * 0.35 + (income - 307050) *
0.386; } else if (status == 1) {
41
ComputeTax.java // Compute tax for married file jointly // Left as exercise } else if (status == 2) { // Compute tax for married separately // Left as exercise } else if (status == 3) { // Compute tax for head of household // Left as exercise } else { System.out.println("Error: invalid status"); System.exit(0); } // Display the result System.out.println("Tax is " + (int)(tax * 100) / 100.0); } }
42
Problem: Guessing Birth Date
The program can guess your birth date. Run to see how it works.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Set1
8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31
Set2
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31
Set3
2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31
Set4
4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31
Set5
+
= 19
43
GuessBirthDate.javaimport java.util.Scanner; public class GuessBirthDate { public static void main(String[] args) { String set1 = " 1 3 5 7\n" + " 9 11 13 15\n" + "17 19 21 23\n" + "25 27 29 31"; String set2 = " 2 3 6 7\n" + "10 11 14 15\n" + "18 19 22 23\n" + "26 27 30 31"; String set3 = " 4 5 6 7\n" + "12 13 14 15\n" + "20 21 22 23\n" + "28 29 30 31"; String set4 = " 8 9 10 11\n" + "12 13 14 15\n" + "24 25 26 27\n" + "28 29 30 31"; String set5 = "16 17 18 19\n" + "20 21 22 23\n" + "24 25 26 27\n" + "28 29 30 31"; int date = 0; // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to answer questions System.out.print("Is your birthdate in Set1?\n"); System.out.print(set1); System.out.print("\nEnter 0 for No and 1 for Yes: "); int answer = input.nextInt(); if (answer == 1) date += 1;
44
GuessBirthDate.java // Prompt the user to answer questions System.out.print("\nIs your birthdate in Set2?\n"); System.out.print(set2); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) date += 2; // Prompt the user to answer questions System.out.print("Is your birthdate in Set3?\n"); System.out.print(set3); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) date += 4;
45
GuessBirthDate.java // Prompt the user to answer questions System.out.print("\nIs your birthdate in Set4?\n"); System.out.print(set4); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) date += 8; // Prompt the user to answer questions System.out.print("\nIs your birthdate in Set5?\n"); System.out.print(set5); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) date += 16; System.out.println("\nYour birthdate is " + date + "!"); } }
46
switch Statementsswitch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0);}
47
switch Statement Flow Chart
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
48
switch Statement Rules
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.
49
switch Statement Rules
The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.
The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.
50
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
Suppose ch is 'a':
animation
51
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
ch is 'a':
animation
52
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
Execute this line
animation
53
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
Execute this line
animation
54
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
Execute this line
animation
55
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}
Next statement;
Execute next statement
animation
56
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}
Suppose ch is 'a':
animation
57
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}
ch is 'a':
animation
58
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}
Execute this line
animation
59
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}
Execute this line
animation
60
Trace switch statement
switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}
Next statement;
Execute next statement
animation
61
Conditional Operatorif (x > 0) y = 1else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;(booleanExpression) ? expression1 : expression2
Ternary operatorBinary operatorUnary operator
62
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);else System.out.println(num + “is odd”);
System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
63
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
64
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.
See URL: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html for a discussion of printf statement and list of specifiers and flags.
65
Frequently-Used Specifiers Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%o octal integer
%x hexadecimal integer
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%g scientific notation (with an exponent) for float
%a hexadecimal with an exponent for float
%s a string "Java is cool"
%n a new line Equivalent to /n
$ argument index which argument to use
66
Frequently-Used Flags
Flag General Character IntegralFloating
PointDate/Time Description
'-' y y y y y The result will be left-justified.
'#' y1 - y3 y -The result should use a conversion-dependent alternate form
'+' - - y4 y - The result will always include a sign
' ' - - y4 y -The result will include a leading space for positive values
'0' - - y y - The result will be zero-padded
',' - - y2 y5 -The result will include locale-specific grouping separators
'(' - - y4 y5 -The result will enclose negative numbers in parentheses
1 Depends on the definition of Formattable.2 For 'd' conversion only.3 For 'o', 'x', and 'X' conversions only.4 For 'd', 'o', 'x', and 'X' conversions applied to Big Integer or 'd' applied to byte, Byte, short,
Short, int and Integer, long, and Long.5 For 'e', 'E', 'f', 'g', and 'G' conversions only. Any characters not explicitly defined
as flags are illegal and are reserved for future extensions.
67
Frequently-Used Specifiers
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
public class MainClass { public static void main(String[] a) { double x = 27.5, y = 33.75; System.out.printf("x = %f y = %g", x, y); }}
x = 27.500000 y = 33.7500
68
printf Examplespublic class MainClass { public static void main(String[] args) { int a = 5, b = 15, c = 255; System.out.printf("a = %d b = %x c = %o", a, b, c); }}
a = 5 b = f c = 377
public class MainClass { public static void main(String[] args) { double x = 27.5, y = 33.75; System.out.printf("x = %15f y = %8g", x, y); }}
x = 27.500000 y = 33.7500
69
printf Examplespublic class MainClass { public static void main(String[] args) { double x = 27.5, y = 33.75; System.out.printf("x = %15.2f y = %14.3g", x, y); }}
x = 27.50 y = 33.8
70
printf Examplespublic class MainClass{ public static void main( String args[] ) { System.out.printf( "%d\n", 26 ); System.out.printf( "%d\n", +26 ); System.out.printf( "%d\n", -26 ); System.out.printf( "%(d\n", -26 ); System.out.printf( "%o\n", 26 ); System.out.printf( "%x\n", 26 ); System.out.printf( "%X\n", 26 ); }}
26 26 -26(26) 32 1a 1A
71
printf Examples
public class MainClass { public static void main( String args[] ) { System.out.printf( "%e\n", 12345678.9 ); System.out.printf( "%e\n", +12345678.9 ); System.out.printf( "%e\n", -12345678.9 ); System.out.printf( "%E\n", 12345678.9 ); System.out.printf( "%f\n", 12345678.9 ); System.out.printf( "%g\n", 12345678.9 ); System.out.printf( "%G\n", 12345678.9 ); }}
1.234568e+07 1.234568e+07 -1.234568e+07 1.234568E+07 12345678.900000 1.23457e+07 1.23457E+07
72
Formatting Output
Items in format section must match items in the item list.public class FormatTest {
/**
* Test format program
*/
public static void main(String[] args) {
boolean b1 = true;
double f1 = 25.2;
int d1 = 65;
System.out.printf("b1 is %b, f1 is %6.2f, d1 is %4d",
b1, f1, d1);
}
}
b1 is true, f1 is 25.20, d1 is 65
73
Format Examplepublic class PrintfDemo {/** * Illustrate several output formats with printf() */public static void main(String[] args) {double q = 1.0/3.0;// Print the number with 3 decimal places.System.out.printf ("1.0/3.0 = %5.3f %n", q);// Increase the number of decimal placesSystem.out.printf ("1.0/3.0 = %7.5f %n", q);// Pad with zeros.q = 1.0/2.0;System.out.printf ("1.0/2.0 = %09.3f %n", q);// Scientific notationq = 1000.0/3.0;System.out.printf ("1000/3.0 = %7.2e %n", q);// More scientific notationq = 3.0/4567.0;System.out.printf ("3.0/4567.0 = %7.2e %n", q);
q = -1.0/0.0;System.out.printf ("-1.0/0.0 = %7.2e %n", q);q = 0.0/0.0;// NaNSystem.out.printf ("0.0/0.0 = %5.2e %n", q);// Multiple argumentsSystem.out.printf ("pi = %5.3f, e = %5.4f %n", Math.PI, Math.E);double r = 1.1;// User the argument index to put the argument values into// different locations within th string.System.out.printf ("C = 2 * %1$5.5f * %2$4.1f, "+ "A = %2$4.1f * %2$4.1f * %1$5.5f %n", Math.PI, r);}}
1.0/3.0 = 0.333 1.0/3.0 = 0.33333 1.0/2.0 = 00000.500 1000/3.0 = 3.33e+02 3.0/4567.0 = 6.57e-04
-1.0/0.0 = -Infinity 0.0/0.0 = NaN pi = 3.142, e = 2.7183 C = 2 * 3.14159 * 1.1, A = 1.1 * 1.1 * 3.14159
Output
74
Operator Precedence
var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)
75
Operator Precedence and Associativity
The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule.
If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative.
76
Operator Associativity
When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative.
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))
77
ExampleApplying 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 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) subtraction
(6) greater than
78
Operand Evaluation Order
Supplement III.A, “Advanced discussions on how an expression is evaluated in the JVM.”
Companion Website
79
(GUI) Confirmation Dialogs
int option = JOptionPane.showConfirmDialog
(null, "Continue");
80
Problem: Guessing Birth Date
GuessBirthDateUsingConfirmationDialogGuessBirthDateUsingConfirmationDialog Run
The program can guess your birth date. Run to see how it works.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Set1
8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31
Set2
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31
Set3
2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31
Set4
4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31
Set5
+
= 19
81
GuessBirthDateUsingConfirmationDialog.javaimport javax.swing.JOptionPane; public class GuessBirthDateUsingConfirmationDialog { public static void main(String[] args) { String set1 = " 1 3 5 7\n" + " 9 11 13 15\n" + "17 19 21 23\n" + "25 27 29 31"; String set2 = " 2 3 6 7\n" + "10 11 14 15\n" + "18 19 22 23\n" + "26 27 30 31"; String set3 = " 4 5 6 7\n" + "12 13 14 15\n" + "20 21 22 23\n" + "28 29 30 31"; String set4 = " 8 9 10 11\n" + "12 13 14 15\n" + "24 25 26 27\n" + "28 29 30 31"; String set5 = "16 17 18 19\n" + "20 21 22 23\n" + "24 25 26 27\n" + "28 29 30 31"; int date = 0;
82
GuessBirthDateUsingConfirmationDialog.java // Prompt the user to answer questions int answer = JOptionPane.showConfirmDialog(null, "Is your birthdate in these numbers?\n" + set1); if (answer == JOptionPane.YES_OPTION) date += 1; answer = JOptionPane.showConfirmDialog(null, "Is your birthdate in these numbers?\n" + set2); if (answer == JOptionPane.YES_OPTION) date += 2; answer = JOptionPane.showConfirmDialog(null, "Is your birthdate in these numbers?\n" + set3); if (answer == JOptionPane.YES_OPTION) date += 4; answer = JOptionPane.showConfirmDialog(null, "Is your birthdate in these numbers?\n" + set4); if (answer == JOptionPane.YES_OPTION) date += 8; answer = JOptionPane.showConfirmDialog(null, "Is your birthdate in these numbers?\n" + set5); if (answer == JOptionPane.YES_OPTION) date += 16; JOptionPane.showMessageDialog(null, "Your birthdate is " + date + "!"); } }