ch2 Elementary Programming

2-1 Introduction

2-2 Writing Simple Programs

參考程式 Listing 2.1 p.49 ComputeArea.java

public class E01_ComputeArea {
	  public static void main(String[] args) {
		    double radius; // Declare radius
		    double area; // Declare area

		    // Assign a radius
		    radius = 20; // New value is radius

		    // Compute area
		    area = radius * radius * 3.14159;

		    // Display results
		    System.out.println("The area for the circle of radius " +
		      radius + " is " + area);
		    
		    System.out.printf("半徑%.0f的圓的面積為%.2f\n", radius, area);
		  }
}

2-3 Reading Input from the Console

Table 2.1 p.51 Methods for Scanner Objects

參考程式 Listing 2.2 p.51 ComputeAreaWithConsoleInput.java

import java.util.Scanner; // Scanner is in the java.util package

public class E02_ComputeAreaWithConsoleInput {

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

		// Prompt the user to enter a radius
		System.out.print("Enter a number for radius: ");
		double radius = input.nextDouble();

		// Compute area
		double area = radius * radius * 3.14159;

		// Display result
		System.out.println("The area for the circle of radius " + radius
				+ " is " + area);
		
		System.out.printf("半徑%.0f的圓的面積為%.2f\n", radius, area);
	}
}

顯示資料的差異

printf format 格式參考

參考程式 Listing 2.3 p.51 ComputeAverage.java

import java.util.Scanner;

public class E03_ComputeAverage {
	 public static void main(String[] args) {
		    // Create a Scanner object
		    Scanner input = new Scanner(System.in);
		    
		    // Prompt the user to enter three numbers
		    System.out.print("Enter three numbers: ");
		    double number1 = input.nextDouble();
		    double number2 = input.nextDouble();
		    double number3 = input.nextDouble();

		    // Compute average
		    double average = (number1 + number2 + number3) / 3;

		    // Display result
		    System.out.printf("三個數目 %f %f %f 的平均=%f\n", number1, number2, number3, average);
		  } 
}

2-4 Identifiers 識別字

2-5 Variables 變數

變數用來儲存「值」以供程式使用或改變

Declaring Variables 變數宣告

int count; // count 為整數變數
double radius; // radius為double浮點數
double interestRate;

int year = 100; // 宣告並給予初值

int month;
month = 9;	// 分成兩個步驟

int day, weekday; // 一次宣告多個變數,用逗點分開,都是 int

int hour=16, minute=30; // 一次宣告多個變數,並給予初值

2-6 Assignment Statements and Assignment Expressions

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;
x = 1;          // Assign 1 to x;
radius = 1.0;   // Assign 1.0 to radius;
a = 'A';        // Assign 'A' to a;

2-7 Named Constants

final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159; 
final int SIZE = 3;

2-8 Numerical Data Types and Operations

Table 2.2 p.56 Numerical Data Types

2-8-1 算數運算符號(Numeric Operator)

參考程式 Listing 2.4 p.58DisplayTime.java

public class E04_DisplayTime {
	  public static void main(String[] args) {
		    Scanner input = new Scanner(System.in);
		    
			int i = 123456789;
			float f = 123456789; //float變數可以承接int值
			double d = 123456789; // 浮點數Literal預設為 double
			System.out.printf("i=%d\n", i);
			System.out.printf("f=%f\n", f); // 7位數,有誤差
			System.out.printf("d=%f\n", d);		    
		    
			int a = 5, b = 2;
			double d2 = 2.0;
			
			System.out.printf("a/b=%d\n",a/b); // 小數點後被捨去
			System.out.printf("a/d2=%f\n",a/d2);
			
			System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
			System.out.println(1.0 - 0.9);

		    // Prompt the user for input
		    System.out.print("Enter an integer for seconds: ");
		    int seconds = input.nextInt();
		 
		    int minutes = seconds / 60; // Find minutes in seconds
		    int remainingSeconds = seconds % 60; // Seconds remaining
		    System.out.println(seconds + " seconds is " + minutes + 
		      " minutes and " + remainingSeconds + " seconds");  
		  }
}

2-8-2 Number Literals

int num = 5;
long bignum = 123145534535L; // 整數Literal預設為 int 
int hexint = 0xA5B6; //16進位整數
int octint = 023; //8進位整數 
double d = 23.4;
float num = 2.0f; //f代表是float類型,預設為 double
double exp = 1.23456E+2; // Scientific Notation

2-8-3 Evaluating Java Expressions

參考 p.60 數學式子與對應的Java Expressions

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

參考程式 Listing 2.5 p.61 FahrenheitToCelsius.java

2-9 Problem: Displaying the Current Time

參考程式 Listing 2.6 p.62 ShowCurrentTime.java

import java.util.Date;
public class E06_ShowCurrentTime {
	 public static void main(String[] args) {
		    // Obtain the total milliseconds since midnight, Jan 1, 1970
		    long totalMilliseconds = System.currentTimeMillis();

		    // Obtain the total seconds since midnight, Jan 1, 1970
		    long totalSeconds = totalMilliseconds / 1000;

		    // Compute the current second in the minute in the hour
		    long currentSecond = (int)(totalSeconds % 60);

		    // Obtain the total minutes
		    long totalMinutes = totalSeconds / 60;

		    // Compute the current minute in the hour
		    long currentMinute = (int)(totalMinutes % 60);

		    // Obtain the total hours
		    long totalHours = totalMinutes / 60;

		    // Compute the current hour
		    long currentHour = (int)(totalHours % 24);

		    // Display results
		    System.out.println("Current time is " + currentHour + ":"
		      + currentMinute + ":" + currentSecond + " GMT");
		    System.out.printf("%1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS\n", totalMilliseconds);
		    
		    Date now = new Date();
		    System.out.format("%1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS\n", now);
		    System.out.printf("%1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS\n", now);
		  }
}

2-10 Shorthand Operators

Table 2.4 p.63 Shorthand Operators

結合指派,將等號左邊的變數,再放到等號右邊

a += b;
a = a + b;
a -= b;
a = a - b

int a=2, b=3;
a -= b + 4;
// a= ?

Table 2.5 p.64 Increment and Decrement Operators

public class E06A_IncDecrementOP {
	public static void main(String[] args) {
		int a = 1, b = 1;
		System.out.printf("a++=%d\n", a++);
		System.out.printf("--b=%d\n", --b);
		System.out.printf("a=%d\n", a);
		System.out.printf("b=%d\n", b);
		// 先加
		a = 1;
		b = ++a;
		System.out.printf("先加 a=%d, b=%d\n", a, b);
		// 後加
		a = 1;
		b = a++;
		System.out.printf("後加 a=%d, b=%d\n", a, b);
		// 先減
		a = 7;
		b = --a;
		System.out.printf("先減 a=%d, b=%d\n", a, b);
		// 後減
		a = 7;
		b = a--;
		System.out.printf("後減 a=%d, b=%d\n", a, b);
	}
}

2-11 Numeric Type Conversion

參考程式 Listing 2.7 p.66 SalesTax.java

import java.util.Scanner;

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

		    System.out.print("Enter purchase amount: "); // 197.55
		    double purchaseAmount = input.nextDouble();
		    
		    double tax = purchaseAmount * 0.06; // 11.853
		    // 小數點2位
		    System.out.println("Sales tax is " + (int)(tax * 100) / 100.0);
		    System.out.printf("Sales tax is %.2f\n", tax);
		    
		    int a = 185;
		    double m = a / 100;
		    double m2 = (double) a / 100;
		    double m3 = a / 100.0;
		    System.out.println("m=" + m);
		    System.out.println("m2=" + m2);
		    System.out.println("m3=" + m3);
		    
		  }
}

2-12 Problem: Computing Loan Payments 貸款

參考程式 Listing 2.8 p.67 ComputeLoan.java

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

		    // Enter yearly interest rate
		    System.out.print("Enter yearly interest rate (年利率), 例如  8.25: ");
		    double annualInterestRate = input.nextDouble();
		    
		    // Obtain monthly interest rate
		    double monthlyInterestRate = annualInterestRate / 1200;

		    // Enter number of years
		    System.out.print(
		      "Enter number of years as an integer(貸款年數), 例如   5: ");
		    int numberOfYears = input.nextInt();
		    
		    // Enter loan amount
		    System.out.print("Enter loan amount(貸款金額), 例如   120000.95: ");
		    double loanAmount = input.nextDouble();
		    
		    // Calculate payment
		    double monthlyPayment = loanAmount * monthlyInterestRate / (1
		      - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
		    double totalPayment = monthlyPayment * numberOfYears * 12;

		    // Display results
		    System.out.println("The monthly payment(每月應付金額) is " + 
		      (int)(monthlyPayment * 100) / 100.0);
		    System.out.println("The total payment(總共付款) is " + 
		      (int)(totalPayment * 100) / 100.0);
		  }
}

2-13 Character Data Type and Operations

char ch1 = 'J'; // 英文單引號
char ch2 = '考'; 
char ch3 = '\u8B49'; //unicode \u 之後4個16進位數字

2-13-1 Unicode and ASCII code

參考程式 Listing 2.9 p.69 DisplayUnicode.java

JOptionPane 為 Swing 架構的對話方塊

import javax.swing.JOptionPane;
public class E09_DisplayUnicode {
	  public static void main(String[] args) {
		    JOptionPane.showMessageDialog(null,
		      "\u6B22\u8FCE \u03b1 \u03b2 \u03b3",
		      "\u6B22\u8FCE Welcome",
		      JOptionPane.INFORMATION_MESSAGE);
		  }
}

2-13-2 Escape Sequences for Special Characters

Table 2.6 p.70 (ppt 44)Java Escape Sequences

System.out.println("He said \"Java is Fun.\"\n");

2-13-3 Casting between char and Numeric Types

public class E09A_CharOp {
	public static void main(String[] args) {
		char ch1 = 'A';
		char uc1 = '\u0041';
		char ch2 = '考';
		int i1 = ch1;
		int i2 = ch2;
		char ch3 = '\u8B49'; // 8B49是16進位,相當於10進位的35657
		System.out.printf("ch1=%c\n", ch1);
		System.out.printf("uc1=%c\n", uc1);
		System.out.printf("ch2=%c\n", ch2);
		System.out.printf("i1=%d\n", i1);
		System.out.printf("i2=%d\n", i2);
		System.out.printf("ch3=%c\n", ch3);

		char ch = (char) 0xAB0041;
		System.out.printf("ch=%c\n", ch);

		ch = (char) 65.25;
		System.out.printf("ch=%c\n", ch);

		int k = (int) 'A'; // unicode of A is assign to k
		System.out.printf("k=%d\n", k); // k=65

		int m = '2' + '3';
		System.out.printf("m=%d\n", m); //

		int n = 2 + 'a';
		System.out.printf("n=%d\n", n); //
		System.out.printf("n is unicode char %c\n", (char) n);

		System.out.println("chapter " + '2'); //
	}
}

2-14 Problem: Monetary Units(換零錢)

參考程式 Listing 2.10 p.72 ComputeChange.java

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

		    // Receive the amount
		    System.out.print(
		      "Enter an amount in double, for example 11.56: ");
		    double amount = input.nextDouble();

		    int remainingAmount = (int)(amount * 100);

		    // Find the number of one dollars
		    int numberOfOneDollars = remainingAmount / 100;
		    remainingAmount = remainingAmount % 100;

		    // 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;

		    // Display results
		    String output = "Your amount " + amount + " consists of \n" +
		      "\t" + numberOfOneDollars + " dollars\n" +
		      "\t" + numberOfQuarters + " quarters\n" +
		      "\t" + numberOfDimes + " dimes\n" +
		      "\t" + numberOfNickels + " nickels\n" +
		      "\t" + numberOfPennies + " pennies";
		    System.out.println(output);
		  }
}

2-15 The String Type

The String type is not a primitive type. It is known as a reference type , 第8章 物件與類別(Objects and Classes)會進一步解說

import java.util.Scanner;

public class E10A_StringOP {
	public static void main(String[] args) {
		String msg = "Welcome to Java";
		String msg2 = "Welcome " + "to " + "Java";
		System.out.printf("msg=%s\n", msg);
		System.out.printf("msg2=%s\n", msg2);

		String msg3 = "Chapter" + 2;
		String msg4 = "Supplement" + 'B';
		System.out.printf("msg3=%s\n", msg3);
		System.out.printf("msg4=%s\n", msg4);
		
		msg += " and Java is fun.";
		System.out.printf("msg=%s\n", msg);
		
		int a=3, b=5;
		System.out.println("a + b =" + a + b);
		System.out.println("a + b =" + (a + b));
		
		Scanner sc = new Scanner(System.in);
		System.out.print("請數入3個字串:");
		String s1 = sc.next();
		String s2 = sc.next();
		String s3 = sc.next();
		System.out.printf("s1=%s\n", s1);
		System.out.printf("s2=%s\n", s2);
		System.out.printf("s3=%s\n", s3);

		System.out.print("請數入一行字:");
		String s = sc.nextLine(); // 為何讀到空字串?
		System.out.printf("s=%s\n", s);

	}
}

2-16 Programming Style 程式寫作樣式 and Documentation 文件說明

2-16-1 Appropriate Comments and Comment Styles 適當的註解與註解方式

2-16-2 Naming Conventions 取名慣例

變數(variables)與方法(methods)第1個字母小寫,例如 radius, area, showInputDialog

類別第1個字母大寫,例如 ComputeArea

常數使用全大寫字母,中間使用底線隔開,例如 MAX_VALUE

2-16-3 Proper Indentation and Spacing Lines 適當的縮排與空行

2-16-4 Block Styles 區塊的樣式

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 區塊的樣式");
	}
}

2-17 Programming Errors

2-17-1 Syntax Errors 語法錯誤

Figure 2.3 p.77 The compiler reports syntax errors

2-17-2 Runtime Errors

2-17-3 Logic Errors

2-17-4 Debugging

2-18 (GUI) Getting Input from Input Dialogs

2-18-1 Converting Strings to Integers

int intValue = Integer.parseInt(intString);

double doubleValue =Double.parseDouble(doubleString);

2-18-2 Using Input Dialog Boxes

參考程式 Listing 2.11 p.80 ComputeLoanUsingInputDialog.java

import javax.swing.JOptionPane;

public class E11_ComputeLoanUsingInputDialog {
	  public static void main(String[] args) {
		    // Enter yearly interest rate
		    String annualInterestRateString = JOptionPane.showInputDialog(
		      "Enter yearly interest rate, for example 8.25:");

		    // Convert string to double
		    double annualInterestRate =
		      Double.parseDouble(annualInterestRateString);

		    // Obtain monthly interest rate
		    double monthlyInterestRate = annualInterestRate / 1200;

		    // Enter number of years
		    String numberOfYearsString = JOptionPane.showInputDialog(
		      "Enter number of years as an integer, \nfor example 5:");

		    // Convert string to int
		    int numberOfYears = Integer.parseInt(numberOfYearsString);

		    // Enter loan amount
		    String loanString = JOptionPane.showInputDialog(
		      "Enter loan amount, for example 120000.95:");

		    // Convert string to double
		    double loanAmount = Double.parseDouble(loanString);

		    // Calculate payment
		    double monthlyPayment = loanAmount * monthlyInterestRate / (1
		      - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
		    double totalPayment = monthlyPayment * numberOfYears * 12;

		    // Format to keep two digits after the decimal point
		    monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
		    totalPayment = (int)(totalPayment * 100) / 100.0;

		    // Display results
		    String output = "The monthly payment is " + monthlyPayment +
		      "\nThe total payment is " + totalPayment;
		    JOptionPane.showMessageDialog(null, output);
		  }
}