Chapter3
3.1 Introduction
The program can decide which statements to execute based on a condition
Boolean value: true or false.
3.2 boolean Data Type
The boolean data type declares a variable with the value either true or false.
//3.2.1
boolean b = true;
i = (int)b;
int i = 1;
boolean b = (boolean)i;
代码段3.2.1不可行,cannot csat from boolean to int.
3.7 Generating Random Numbers
You can use Math.random() to obtain a random double value between 0.0 and 1.0,
excluding 1.0.
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));
}
}
}
3.8 Case Study: Computing Body Mass Index
You can use nested if statements to write a program that interprets body mass index.
3.10 Logical Operators
The logical operators !, &&, ||, and ^ can be used to create a compound Boolean
expression.
3.13 switch Statements
A switch statement executes statements based on the value of a variable or an
expression.
3.14 Conditional Expressions
A conditional expression evaluates an expression based on a condition.
if (x > 0)
y = 1;
else
y = -1;
Alternatively, as in the following example, you can use a conditional expression to achieve
the same result
y = (x > 0) ? 1 : -1;
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");
3.15 Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are
evaluated.
3.16 Debugging
Debugging is the process of finding and fixing errors in a program.