第三章
基本資料型式
3.1 數值型式
每一變數都具有資料型式。
界定一個變數,必須定其型式及名稱,同時也可規定其初值。 例如,
int nickels = 3;
- 整數(integer): no fractional part
1, -4, 0
整數變數用 int 宣告
- 浮點(floating-point)數:
0.5, -3.11111, 4.3E24, 1E-14
浮點數變數用 double (倍準, double precision)宣告
Purse Class Interface
public class Purse
{
public void addNickels(int count) . . .
public void addDimes(int count) . . .
public void addQuarters(int count) . . .
public double getTotal(int count) . . .
. . .
private int nickels;
private int dimes;
private int quarters;
}
實現 getTotal 方法
public class Purse
{
public double getTotal()
{
return nickels * 0.05
+ dimes * 0.1 + quarters * 0.25;
}
private int nickels;
private int dimes;
private int quarters;
}
* = multiplication
3.2 指定(assignment)敘述
v = exp;
v 為變數, 而 exp 為陳式(expression)。
陳式是由運算元(operand)和運算子(operator)組成。
運算元可以是變數或常數。 變數在使用前,必須先宣告其資料型式。
public Purse()
{
nickels = 0;
dimes = 0;
quarters = 0;
}
public void addNickels(int count)
{
nickels = nickels + count;
}
指定(assignment)敘述
Increment/Decrement
nickels++ is the same as nickels = nickels + 1
nickels-- decrements the contents of the variable.
3.3 Constants
public double getTotal()
{
final double NICKEL_VALUE = 0.05;
final double DIME_VALUE = 0.1;
final double QUARTER_VALUE = 0.25;
return nickels * NICKEL_VALUE
+ dimes * DIME_VALUE + quarters * QUARTER_VALUE;
}
Class Constants
public class Purse
{
. . .
public double getTotal()
{
return nickels * NICKEL_VALUE
+ dimes * DIME_VALUE + quarters * QUARTER_VALUE;
}
private static final double NICKEL_VALUE = 0.05;
private static final double DIME_VALUE = 0.1;
private static final double QUARTER_VALUE = 0.25;
. . .
}
In methods of other classes, the constant is
Purse.DIME_VALUE
Syntax 3.1: Constant Definition
Example: Purpose:
|
In a method:
final typeName variableName= expression
;
In a class:
accessSpecifier static final typeName variableName
= expression; |
Example:
|
final double NICKEL_VALUE =0.05;
public static final double LITERS_PER_GALLON =3.785; |
Purpose:
To define a constant of a particular type |
File Purse.java
/**
A purse computes the total value of a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
nickels = 0;
dimes = 0;
quarters = 0;
}
/**
Add nickels to the purse.
@param count the number of nickels to add
*/
public void addNickels(int count)
{
nickels = nickels + count;
}
/**
Add dimes to the purse.
@param count the number of dimes to add
*/
public void addDimes(int count)
{
dimes = dimes + count;
}
/**
Add quarters to the purse.
@param count the number of quarters to add
*/
public void addQuarters(int count)
{
quarters = quarters + count;
}
/**
Get the total value of the coins in the purse.
@return the sum of all coin values
*/
public double getTotal()
{
return nickels * NICKEL_VALUE
+ dimes * DIME_VALUE + quarters * QUARTER_VALUE;
}
private static final double NICKEL_VALUE = 0.05;
private static final double DIME_VALUE = 0.1;
private static final double QUARTER_VALUE = 0.25;
private int nickels;
private int dimes;
private int quarters;
}
File PurseTest.java
/**
This program tests the Purse class.
*/
public class PurseTest
{
public static void main(String[] args)
{
Purse myPurse = new Purse();
myPurse.addNickels(3);
myPurse.addDimes(1);
myPurse.addQuarters(2);
double totalValue = myPurse.getTotal();
System.out.print("The total is ");
System.out.println(totalValue);
}
}
3.4 Arithmetic and Mathematical Functions
Division and Remainder
- / is the division operator
- If both arguments are integers, the result is an integer. The remainder
is discarded
- 7.0 / 4 = 1.75
7 / 4 = 1
- Get the remainder with % (pronounced "modulo")
7 % 4 = 3
Mathematical Functions
Math.sqrt(x)
|
square root
|
Math.pow(x, y)
|
power xy
|
Math.exp(x)
|
ex
|
Math.log(x)
|
natural log
|
Math.sin(x), Math.cos(x), Math.tan(x)
|
sine, cosine, tangent (x in radian)
|
Math.round(x)
|
closest integer to x
|
Analyzing an Expression
3.5 Calling Static Methods
Syntax 3.2: Static Method Call
|
ClassName. methodName(
Tparameters)
|
Example:
Purpose:
To invoke a static method (a method that doesn't operate on an object) and
supply its parameters. |
3.6 型式轉換
- = 號兩邊的資料型式必須相同
double total = "a lot"; // no
- 使用 “cast” (int) 將浮點數值換成整數值:
int pennies = (int)(total * 100);
Cast discards fractional part.
- 捨入(rounding)用 Math.round:
int dollar = (int)Math.round(total);
Syntax 3.3 : Cast
Example:
|
(int)(x + 0.5)
(int)Math.round(100 * f)
|
Purpose:
To convert an expression to a different type |
3.7 字串(Strings)
- 字串常數:
"Carl"
- 字串變數:
String name = "Carl";
- 字串長度:
int n = name.length();
Concatenation
連接兩字串, 用運算子 + :
- String fname = "Harry";
String lname = "Hacker";
String name = fname + lname;
- name is "HarryHacker"
- 假如 + 的運算元中只有一個是字串,另一個則換成字串:
String a = "Agent";
String name = a + 7;
- name is "Agent7"
字串和數字的轉換
- 換成數字:
int n = Integer.parseInt(str);
double x = Double.parseDouble(str);
- 換成字串:
String str = "";
str = Integer.toString(n);
Substrings
- String greeting = "Clown";
String sub = greeting.substring(1, 4);
- Supply start and “past the end” position
- First position is at 0
0C1l2o3w4n
- substring length = “past the end” - start
3.8 讀取輸入值
- String input = JOptionPane.showInputDialog(prompt)
- 必要時將字串換成數字:
int count = Integer.parseInt(input);
- 假如輸入的不是數字, 則轉換時丟出例外(exception)--see
chapter 15
- 任一程式,只要使用到 JOptionPane, 就必須在 main 方法中加入下列敘述:
System.exit(0)
對話式的輸入窗口
File InputTest.java
import javax.swing.JOptionPane;
/**
This program tests input from an input dialog.
*/
public class InputTest
{
public static void main(String[] args)
{
Purse myPurse = new Purse();
String input = JOptionPane.showInputDialog("How many nickels do you have?");
int count = Integer.parseInt(input);
myPurse.addNickels(count);
input = JOptionPane.showInputDialog("How many dimes do you have?");
count = Integer.parseInt(input);
myPurse.addDimes(count);
input = JOptionPane.showInputDialog("How many quarters do you have?");
count = Integer.parseInt(input);
myPurse.addQuarters(count);
double totalValue = myPurse.getTotal();
System.out.println("The total is " + totalValue);
System.exit(0);
}
}
File ConsoleInputTest.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/**
This program tests input from a console window.
*/
public class ConsoleInputTest
{
public static void main(String[] args) throws IOException
{
Purse myPurse = new Purse();
BufferedReader console = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("How many nickels do you have?");
String input = console.readLine();
int count = Integer.parseInt(input);
myPurse.addNickels(count);
System.out.println("How many dimes do you have?");
input = console.readLine();
count = Integer.parseInt(input);
myPurse.addDimes(count);
System.out.println("How many quarters do you have?");
input = console.readLine();
count = Integer.parseInt(input);
myPurse.addQuarters(count);
double totalValue = myPurse.getTotal();
System.out.println("The total is " + totalValue);
}
}
3.9 字元
- char: 字元型式 -- 單一 Unicode 字元
- Character 常數用單引號(single quotes):
'A', '\n', '\u00E9'
- 'A' 和 "A" 不同
- 字串的 charAt 方法用以取出字串中的一個字元, 如
"Hello".charAt(0) is 'H'
Comparing Primitive Types and Objects
拷貝數字
- double balance1 = 1000;
double balance2 = balance1;
balance2 = balance2 + 500;
- 變更 balance2 的數值, 並未影響 balance1
拷貝物件的參考(Reference)
- BankAccount account1 = new BankAccount(1000);
BankAccount account2 = account1;
account2.deposit(500);
- account2 內儲值的更動, 也反應在 account1
- 物件變數儲存的是物件的參考, 並不是物件。