3.2 boolean Data Type
The boolean data type declares a variable with the value either trueor false.
A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare Boolean variables. A booleanvariable can hold one of the two values: trueorfalse. trueandfalseare literals, just like a number such as 10. They are treated as reserved words and cannot be used as identifiers in the program.
LISTING3.1AdditionQuiz.java
import 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 number = input.nextInt();
int answer = number1+number2;
System.out.println(
number1 + " + " + number2 + " = " + number + " is " +
(number1 + number2 == answer));
}
}
3.3 if Statements
if (boolean-expression) {
statement(s);
}
LISTING3.2SimpleIfDemo.java
import java.util.Scanner;
public class SimpleIfDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0)
System.out.println("HiFive");
if (number % 2 == 0)
System.out.println("HiEven");
}
}
3.4 Two-Way if-else Statements
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
3.5 Nested if and Multi-Way if-else Statements
if (i > k) {
if(j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
Example:
3.6 Common Errors and Pitfalls
Errors
1、忘记加大括号;
2、乱加分号;
3、冗余的判断
4、受排版误导,搞错了if…else的配对关系;
5、期望浮点数严格相等;
6、用足够近来代替相等
Pitfalls
1、判断条件可作为布尔值直接赋值
2、两个分支都会执行到的语句最好提出来
转化为:
3.7 Generating Random Numbers
1、int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() / 7 % 10);
2、int number1 = (int)(Math.random() * 10);
LISTING3.3SubtractionQuiz.java
import 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.");
System.out.println(number1 + " - " + number2 + " should be " + (number1 - number2));
}
}
}
LISTING3.4 ComputeAndInterpretBMI.java
import java.util.Scanner;
public class ComputeAndInterpretBMI {
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 weightInKilograms = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilograms /
(heightInMeters * heightInMeters);
// Display result
System.out.println("BMI is " + bmi);
if (bmi < 18.5)
System.out.println("Underweight");
else if (bmi < 25)
System.out.println("Normal");
else if (bmi < 30)
System.out.println("Overweight");
else
System.out.println("Obese");
}
}
3.10 Logical Operators
!(condition1 && condition2) is the same as !condition1 || !condition2
!(condition1 || condition2) is the same as !condition1 && !condition2
For example, ! (number % 2 == 0 && number % 3 == 0) can be simplified using an equivalent expression: (number % 2 != 0 || number % 3 != 0)
As another example, !(number == 2 || number == 3) is better written as
number != 2 && number != 3
When evaluating p1 && p2, Java first evaluates p1and then, ifp1is true, evaluatesp2; ifp1isfalse, it does not evaluatep2. When evaluatingp1 || p2, Java first evaluatesp1and then, if p1 is false, evaluatesp2; ifp1is true, it does not evaluatep2. In programming language terminology,&&and||are known as theshort-circuitor lazy operators. Java also provides the unconditional AND (&) and OR (|) operators, which are covered in Supplement III.C for advanced readers.
3.11 Case Study: Determining Leap Year
LISTING3.7 LeapYear.java
import 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
System.out.println(year + " is a leap year? " + isLeapYear);
}
}
3.12 Case Study: Lottery
Suppose you want to develop a program to play lottery. The program 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 rules:
1. If the user input matches the lottery number in the exact order, the award is $10,000.
2. If all digits in the user input match all digits in the lottery number, the award is $3,000.
3. If one digit in the user input matches a digit in the lottery number, the award is $1,000.
Note that the digits of a two-digit number may be 0. If a number is less than10, we assume the number is preceded by a0to form a two-digit number. For example, number8is treated as08 and number 0is treated as00in the program. Listing 3.8 gives the complete program.
LISTING3.8Lottery.java
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
// Generate a lottery number
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 (two digits): ");
int guess = input.nextInt();
// Get digits from lottery
int lotteryDigit1 = lottery / 10;
int lotteryDigit2 = lottery % 10;
// Get digits from guess
int guessDigit1 = guess / 10;
int guessDigit2 = guess % 10;
System.out.println("The lottery number is " + lottery);
// Check the guess
if (guess == lottery)
System.out.println("Exact match: you win $10,000");
else if (guessDigit2 == lotteryDigit1
&& guessDigit1 == lotteryDigit2)
System.out.println("Match all digits: you win $3,000");
else if (guessDigit1 == lotteryDigit1
|| guessDigit1 == lotteryDigit2
|| guessDigit2 == lotteryDigit1
|| guessDigit2 == lotteryDigit2)
System.out.println("Match one digit: you win $1,000");
else
System.out.println("Sorry, no match");
}
}
The program generates a lottery using the random()method (line 6) and prompts the user to enter a guess (line 11). Note thatguess % 10obtains the last digit fromguessand guess / 10obtains the first digit fromguess, sinceguessis a two-digit number (lines 18–19). The program checks the guess against the lottery number in this order:
1. First, check whether the guess matches the lottery exactly (line 24).
2. If not, check whether the reversal of the guess matches the lottery (lines 26–27).
3. If not, check whether one digit is in the lottery (lines 29–32).
4. If not, nothing matches and display "Sorry, no match"(lines 34–35).
3.13 Switch Statements
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 statement observes the following rules:
■ The switch-expressionmust yield a value ofchar,byte,short,int, orString type and must always be enclosed in parentheses. (ThecharandStringtypes will be introduced in the next chapter.)
■ The value1, . . ., andvalueNmust have the same data type as the value of theswitchexpression.
Note that value1, . . ., andvalueNare constant expressions, meaning that they cannot contain variables, such as1 + x.
■ When the value in a casestatement matches the value of theswitch-expression, the statementsstarting from this caseare executed until either a breakstatement or the end of theswitchstatement is reached.
■ The defaultcase, which is optional, can be used to perform actions when none of the specified cases matches theswitch-expression.
■ The keyword breakis optional. Thebreakstatement immediately ends theswitch Statement.
LISTING3.9ChineseZodiac.java
import java.util.Scanner;
public class ChineseZodiac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
switch (year % 12) {
case 0: System.out.println("monkey"); break;
case 1: System.out.println("rooster"); break;
case 2: System.out.println("dog"); break;
case 3: System.out.println("pig"); break;
case 4: System.out.println("rat"); break;
case 5: System.out.println("ox"); break;
case 6: System.out.println("tiger"); break;
case 7: System.out.println("rabbit"); break;
case 8: System.out.println("dragon"); break;
case 9: System.out.println("snake"); break;
case 10: System.out.println("horse"); break;
case 11: System.out.println("sheep");
}
}
}
3.14 Conditional Expression
if (x > 0)
y = 1
else
y = -1;
等价于:
y = (x > 0) ? 1 : -1;
条件表达式的语法(小括号不是必须的,不过为了可读性最好加上):
(boolean-expression) ? expression1 : expression2
条件运算符可以简化代码,例:
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");
3.15 Operator Precedence and Associativity
TABLE 3.8Operator Precedence Chart
Precedence Operator(优先级逐行降低)
var++ and var––(Postfix)
+, –(Unary plus and minus),++varand––var(Prefix)
(type) (Casting)
!(Not)
*, /,%(Multiplication, division, and remainder)
+, –(Binary addition and subtraction)
<, <=,>,>=(Relational)
==, !=(Equality)
^ (Exclusive OR)
&& (AND)
|| (OR)
=, +=,–=,*=,/=,%=(Assignment operator)
Example:
3.16 Debugging
Debugging is the process of finding and fixing errors in a program.
As mentioned in Section 1.10.1, syntax errors are easy to find and easy to correct because the compiler gives indications as to where the errors came from and why they are there. Runtime errors are not difficult to find either, because the Java interpreter displays them on the console
when the program aborts. Finding logic errors, on the other hand, can be very challenging. Logic errors are calledbugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to help pinpoint the part of the program where the bug is located. You canhand-tracethe program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. These approaches might work for debugging a short, simple program, but for a large, complex program, the most effective approach is to use a debugger utility.
JDK includes a command-line debugger, jdb, which is invoked with a class name. jdb is itself a Java program, running its own copy of Java interpreter. All the Java IDE tools, such as Eclipse and NetBeans, include integrated debuggers. The debugger utilities let you follow the execution of a program. They vary from one system to another, but they all support most of the following helpful features.
■ Executing a single statement at a time:The debugger allows you to execute one statement at a time so that you can see the effect of each statement.
■ Tracing into or stepping over a method:If a method is being executed, you can ask the debugger to enter the method and execute one statement at a time in the method, or you can ask it to step over the entire method. You should step over the entire method if you know that the method works. For example, always step over system-supplied methods, such as System.out.println.
■ Setting breakpoints: You can also set a breakpoint at a specific statement. Your program pauses when it reaches a breakpoint. You can set as many breakpoints as you want. Breakpoints are particularly useful when you know where your programming error starts. You can set a breakpoint at that statement and have the program execute until it reaches the breakpoint.
■ Displaying variables: The debugger lets you select several variables and display their values. As you trace through a program, the content of a variable is continuously updated.
■ Displaying call stacks: The debugger lets you trace all of the method calls. This feature is helpful when you need to see a large picture of the program-execution flow.
■ Modifying variables: Some debuggers enable you to modify the value of a variable when debugging. This is convenient when you want to test a program with different samples but do not want to leave the debugger.
CHAPTER 3 SUMMARY
1. A booleantype variable can store atrueorfalsevalue.
2. The relational operators (<,<=,==,!=,>,>=) yield a Boolean value.
3. Selection statementsare used for programming with alternative courses of actions. There are several types of selection statements: one-wayifstatements, two-way if-elsestatements, nestedifstatements, multi-wayif-elsestatements,switch statements, and conditional expressions.
4. The various ifstatements all make control decisions based on aBoolean expression. Based on thetrueorfalseevaluation of the expression, these statements take one of two possible courses.
5. The Boolean operators&&,||,!, and^operate with Boolean values and variables.
6. When evaluating p1 && p2, Java first evaluatesp1and then evaluatesp2 if p1is
true; if p1isfalse, it does not evaluatep2. When evaluatingp1 || p2, Java first evaluatesp1and then evaluatesp2 if p1isfalse; ifp1istrue, it does not evaluate p2. Therefore,&&is referred to as theconditionalor short-circuit AND operator, and ||is referred to as theconditionalor short-circuit OR operator.
7. The switchstatement makes control decisions based on a switch expression of type char,byte,short,int, orString.
8. The keyword breakis optional in a switch statement, but it is normally used at the
end of each case in order to skip the remainder of the switchstatement. If the break statement is not present, the nextcasestatement will be executed.
9. The operators in expressions are evaluated in the order determined by the rules of parentheses,operator precedence, andoperator associativity.
10. Parentheses can be used to force the order of evaluation to occur in any sequence.
11. Operators with higher precedence are evaluated earlier. For operators of the same precedence, their associativity determines the order of evaluation.
12. All binary operators except assignment operators are left-associative; assignment operators are right-associative.