ch3 Selections

3-1 Introduction

計算圓面積時,半徑小於0時,該如何處理?

public class EX00_CircleArea {
	public static void main(String[] args) {
		int radius = -3;
		if (radius < 0) {
			System.out.println("圓的半徑不能小於0");
		} else {
			double area = radius * radius * Math.PI;
			System.out.printf("面積=%.2f", area);
		}
	}
}

3-2 boolean Data Type

p.96 Table 3.1 Comparison Operations

3-3 Problem: A Simple Math Learning Tool

參考 p.97 程式 Listing 3.1 AdditionQuiz.java

public class EX01_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));
	}
}

3-4 if Statements

3-4-1 One-Way if Statements

3-6 有 Two-Way if Statements

if (boolean-expression) { // 可以計算(評估)的boolean運算式,可以是true, false
	statement(s); // 若為true, 則執行這些敘述(statement)
}

參考 p.99 程式 Listing 3.2 SimpleIfDemo.java

public class EX02_SimpleIfDemo {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter an integer: ");
		int number = input.nextInt();

		// test input 12, 15, 11, 30
		if (number % 5 == 0)
			System.out.println("HiFive");

		if (number % 2 == 0)
			System.out.println("HiEven");
	}
}

3-5 Problem: Guessing Birthdays

參考 p.100 程式 Listing 3.3 GuessBirthday.java

3-6 Two-Way if Statements

if (boolean-expression) { // 可以計算(評估)的boolean運算式,可以是true, false
	statement(s)-for-true; // 若為true, 則執行這些敘述(statement)
} else {
	statement(s)-for-false; // 若為false, 則執行這些敘述(statement)
}	
public class EX03A_EvenOdd {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("請數入一個整數:");
		int num = input.nextInt();
		if (num % 2 == 0) {
			System.out.printf("%d 是偶數\n", num);
		} else {
			System.out.printf("%d 是偶數\n", num);
		}
	}
}

3-7 Nested if Statements

p.104 Figure 3.4 A preferred format for multiple alternative if statements is shown in (b)

3-8 Common Errors in Selection Statements

參考 p.105 Error 1, 2, 3, 4

3-9 Problem: An Improved Math Learning Tool

參考 p.107 程式 Listing 3.4 SubtractionQuiz.java

3-10 Problem: Computing Body Mass Index

參考 p.108 程式 Listing 3.5 ComputeBMI.java

public class EX05_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 weightInKilogram = weight * KILOGRAMS_PER_POUND;
		double heightInMeters = height * METERS_PER_INCH;
		double bmi = weightInKilogram / (heightInMeters * heightInMeters);

		// Display result
		System.out.printf("Your BMI is %5.2f\n", bmi);
		if (bmi < 16)
			System.out.println("You are seriously underweight");
		else if (bmi < 18)
			System.out.println("You are underweight");
		else if (bmi < 24)
			System.out.println("You are normal weight");
		else if (bmi < 29)
			System.out.println("You are overweight");
		else if (bmi < 35)
			System.out.println("You are seriously overweight");
		else
			System.out.println("You are gravely overweight");
	}
}

3-11 Problem: Computing Taxes

參考 p.110 程式 Listing 3.6 ComputeTax.java

3-12 Logical Operators

p.112 Table 3.3 Boolean Operators

p.112 Table 3.4 Truth Table for Operator !

p.112 Table 3.5 Truth Table for Operator &&

p.113 Table 3.6 Truth Table for Operator ||

p.113 Table 3.7 Truth Table for Operator ^

參考 p.113 程式 Listing 3.7 TestBooleanOperators.java

public class EX07_TestBooleanOperators {
	public static void main(String[] args) {
		// Create a Scanner
		Scanner input = new Scanner(System.in);

		// Receive an input
		System.out.print("Enter an integer: ");
		int number = input.nextInt();

		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)));
	}
}
public class E07A_LogicOP {
	public static void main(String[] args){
		
		// short-circuit 與 side effect 
		int score = 53, miss=3;
		boolean pass;
		pass = score >= 60 && miss++ < 5; // short-cut
		System.out.printf("&& pass=%b, miss=%d\n", pass, miss);
		
		score=53; miss=3;
		pass = score >= 60 & miss++ < 5;
		System.out.printf("& pass=%b, miss=%d\n", pass, miss);
		
		// And
		int money = 30000; //現金
		int day = 7; //假期天數
		System.out.print("澳洲團成行:");
		System.out.println(money>=40000 && day>=7);

		// Or
		boolean isDiesel = true;
		int cc = 1800; //排氣量
		System.out.print("購買汽車:");
		System.out.println(isDiesel || cc<=1500);

		// Xor
		boolean MassageChair = true; //送按摩椅
		boolean skylight = true; //送天窗
		System.out.print("成交:");
		System.out.println(MassageChair ^ skylight);
		
		// Not
		int age = 16; //年齡
		System.out.print("未滿18歲:");
		System.out.println(!(age>=18));		
	}
}

p.114 Caution and Note

// error
1 <= Num <= 31
// ok
(1 <= Num) && (Num <= 31)

3-13 Problem: Determining Leap Year

參考 p.115 程式 Listing 3.8 LeapYear.java

public class E08_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);
	}
}

3-14 Problem: Lottery

參考 p.115 程式 Listing 3.8 Lottery.java

import java.util.Scanner;

public class EX09_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.printf("magic number = %d\n", lottery);
		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");
	}
}

3-15 switch Statement

switch (switch-expression) { // char, byte, short, int
case value1:
	statement(s)1;
	break;
case value2:
	statement(s)2;
	break;
	...
case valueN:
	statement(s)N;
	break;
	...
default:
	statement(s)-for-default;
}
public class EX09A_Switch {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("請輸入月份:  ");
		int month = input.nextInt();
		int days;
		switch (month) {
		case 1:
			days = 31;
			System.out.printf("month=%d, days=%d\n", month, days);
			break;
		case 4:
			days = 30;
			System.out.printf("month=%d, days=%d\n", month, days);
			break;
		default:
			days = 0;
			System.out.printf("month=%d, days=%d\n", month, days);
		}
	}
}

3-16 Conditional Expressions (ternary operator 三元運算子)

int max, num1=1, num2=2;
// following statement
if (num1 > num2) {
	max = num1;
} else {
	max = num2;
}
// equal
max = (num1 > num2) ? num1 : num2;

3-17 Formatting Console Output

Dispaly only two digits after the decimal point in a floating-point value

double x = 2.0 / 3;
System.out.println("x=" + (int) (x * 100) / 100.0);
// or
System.out.printf("x=%.2f\n",x);

p.120 Table 3.8 Frequently Used Specifiers

  1. %b boolean
  2. %c character
  3. %d decimal
  4. %f floating point
  5. %e scientific notation
  6. %s string

p.120 Table 3.9 Examples of Specifying Width and Precision

  1. %5c
  2. %6d
  3. %10.2f
  4. %,13.0f
  5. %12s
  6. %-12s

p.121 Caution and Tips and 圖形解說

3-18 Operator Precedence and Associativity

p.122 Table 3.10 Operator Precedence Chart 或課本 p 736, 附錄C

Operators

3-19 (GUI) Confirmation Dialogs

參考 p.123 程式 Listing 3.10 GuessBirthdayUsingConfirmationDialog.java