1 / 64

Simple Data Objects

Simple Data Objects. Lecturer :楊昌樺. Outline. 數字物件( Number ) 數學物件( Math ) 陣列物件( Array ) Your Turn 字元( Character ) 字串( String ) 字串緩衝區( StringBuffer ) Your Turn. 數字( Number ). 數字基本形態與數字物件的不同. 用上一堂的課的語法創造物件. int x = 3;. Integer x = new Integer(3);. x. 0 x5678. 0 x1234. x. 3.

bendek
Download Presentation

Simple Data Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Simple Data Objects Lecturer:楊昌樺

  2. Outline • 數字物件(Number) • 數學物件(Math) • 陣列物件(Array) • Your Turn • 字元(Character) • 字串(String) • 字串緩衝區(StringBuffer) • Your Turn

  3. 數字(Number) • 數字基本形態與數字物件的不同 用上一堂的課的語法創造物件 int x = 3; Integer x = new Integer(3); x 0x5678 0x1234 x 3 0x5678 3 toString() x = 3; 缺少操作此資料的函數 / 方法 x->Integer(3); 資料與方法同在,方便

  4. 數字(Number) • 基本型態類別架構

  5. 數字(Number) • 基本型態類別 • Number (java.lang) • 所有 數字物件 之父類別 • Byte, Short, Integer, Long (java.lang) • 對應 byte, short, int, long 等 Primitive Type • Float, Double (java.lang) • 對應 float, double 等 Primitive Type • BigInteger, BigDecimal (java.math) • 允許程式師儲存 Primitive Type 無法表示的數值長度及精確度

  6. 數字(Number) • 基本型態類別 • 為了完整對應所有的 Primitive Type,下列三者基本型態類別被創造出來,但不繼承 java.lang.Number • Boolean (java.lang) boolean • Character (java.lang) char • Void (java.lang)  void

  7. 數字(Number) • Integer / Long 常用方法 (比較) • int compareTo(Integer obj);int compareTo(Long obj); • 比較兩個物件的內容,傳回值是整數,0 表示相等,< 0 表示參數物件比較大,> 0 表示參數物件比較小 • boolean equals(Object obj); • 比較兩個物件是否相等 • 範例 • Integer i1 = new Integer(3);Integer i2 = new Integer(4);i1.compareTo(i2);i1.equals(i2);

  8. 數字(Number) • Example: NumberDemo.java Float floatOne = new Float(14.78f - 13.78f); Float floatTwo = Float.valueOf("1.0"); Double doubleOne = new Double(1.0);

  9. 數字(Number) • Integer / Long 常用方法 (數字轉字串) • String toString(); • static String toBinaryString(int i);static String toBinaryString(long l); • static String toOctalString(int i);static String toOctalString(long l); • static String toHexString(int i);static String toHexString(long l);

  10. 數字(Number) • Example: NumberDemo.java Integer i = new Integer(100); System.out.println("Decimal of 100: " + i.toString()); System.out.println("Hexidecimal of 100: " + Integer.toHexString(i.intValue())); System.out.println("Octal of 100: " + Integer.toOctalString(i.intValue())); System.out.println("Binary of 100: " + Integer.toBinaryString(i.intValue()));

  11. 數字(Number) • Float / Double 常用屬性 • MAX_VALUE • 傳回兩者的極大值 • MIN_VALUE • 傳回兩者的極小值 • POSITIVE_INFINITY • 正無限大。1.0 / 0.0 會得到此值 • NEGATIVE_INFINITY • 負無限大。-1.0 / 0.0 會得此值 • NaN (Not a Number) • 非數字。可能為 0.0 / 0.0 的結果或虛數 的運算結果

  12. 數字(Number) • Float / Double 常用方法(methods) • boolean isInfinite(); • 如果是 POSITIVE_INFINITY 或 NEGATIVE_INFINITY 則傳回 true • boolean isNaN(); • 如果是 NaN,則傳回 true • 不用擔心ArithmeticException之問題

  13. 數字(Number) • Example: NumberDemo.java Float f1 = new Float(1.0/0.0); Float f2 = new Float(-1.0/0.0); Float f3 = new Float(0.0/0.0); System.out.println("The result of 1.0 / 0.0: " + f1.toString()); System.out.println("The result of -1.0 / 0.0: " + f2.toString()); System.out.println("The result of 0.0 / 0.0: " + f3.toString());

  14. 數字(Number) • 字串轉成數字 • 在數字類別中,各自提供一個 valueOf() 的 class method 來將字串轉成該類別的物件 • 例如:NumberDemo.java • 字串轉成數字 • int Integer.parseInt(String) • long Long.parseLong(String) • double Double.parseDouble(String) • float Float.parseFloat(String)

  15. 數字(Number) • Example: NumberDemo.java String str1 = "17.5"; String str2 = "9.8"; String str3 = "7.8"; float a = Float.valueOf(str1).floatValue(); float b = Float.valueOf(str2).floatValue(); float c = Float.parseFloat(str3); System.out.println("a + b = " + (a+b)); System.out.println("c = " + c);

  16. 數學(Math) • 計算亂數、最大和最小值

  17. 數學(Math) • Example: MathMaxMin.java System.out.println("亂數random(): "+Math.random()); // 0-19的亂數 int num = (int)(Math.random()*20); System.out.println("0-20亂數: " + num); // 1-500的亂數 num = (int)(Math.random()*500 + 1); System.out.println("1-500亂數: " + num);

  18. 數學(Math) • Math Class • 與數字有相關的類別,其提供了一般的數學運算 • 如:計算三角函數,計算數字的 N 次方 • Math 類別中的 methods 都是 class methods,所以在呼叫時,直接使用類別名稱呼叫,如:Math.round(34.87) • 提供眾多的數學運算,詳細請看 Java API • Example: MathDemo.java

  19. x[0] x[1] x[2] x[3] x[4] int x int x[5] 陣列(Array) • 定義: • 一群相同資料型態變數的資料結構 • 一個變數: int x; • 一個陣列: int x[] = new int[5]; • 其實我們一直在用陣列 • String[] args; // 一個字串陣列 • 記憶體中的差異

  20. 陣列(Array) • 陣列 Array • 陣列為一種 Reference 資料型態,是可以儲存多個同一種資料的結構,在宣告的同時必須指定長度且不可再改變 • 元素:陣列中儲存的資料,可藉由索引值(index)存取其值,索引值由 0 開始 • 因為它不屬於 “基本型態” (Primitive),故宣告之後 Java 並不會自動為該變數配置記憶體,您必須自行用 new 指令後才能使用。

  21. 陣列(Array) • 陣列宣告 • 語法:DataType[] arrayName; 例:int[] anArray; String[] anArrayOfStrings; • 建立陣列(使用 new運算子) • 語法:arrayName = new DataType[arraySize]; 例:anArray = new int[10]; String[] anArrayOfStrings = new String[10]; • 存取陣列元素 • 語法:arrayName[index] 例:anArray[0] = 3; anArrayOfStrings[1] = “We are studying Java!!”;

  22. 陣列(Array) • 設定陣列初值 • 一個一個指定 如:anArray[1] = 1 • 迴圈, 如:for(int i = 0; i < anArray.length; i++) { anArray[i] = i; } • 在建立時給定初值: • DataType[] arrayName = {val01, val02, val03, …}; 例如 • String[] Month = {"January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November", "December"};

  23. 陣列(Array) • 取得陣列長度 • 語法:arrayName.length • 注意:不用在 length 後加上小括弧,因為此處的 length 並不是 method,而是陣列的一種屬性。和 String 類別中的 length() 並不同。 • 可以用一個陣列的長度來控制迴圈 如:for(int i = 0; i < anArray.length; i++) { … } 或是 for(int i = anArray.length – 1; i >= 0; i--) { … }

  24. 陣列(Array) • Example: ArrayDemo.java // 宣告一個 int 的陣列 int[] anArray; // 用 new 來產生一個有 10 個 int 空間的陣列 anArray = new int[10]; // 依序將陣列給於初值且印出來 for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); }

  25. 陣列(Array) • 物件陣列 • 陣列可以存放 reference 型態(物件)和 primitive 型態(基本型態)的資料 例如: String[] anArray ={“One”, “Two”, “Three”}; • 而此時 anArray[0], anArray[1], anArray[2] 都是一個 String 物件,都具有物件所屬的方法跟屬性 如: anArray[0].toUpperCase() • Example: ArrayOfStringsDemo.java

  26. 陣列(Array) • 當建立的一個物件陣列時,若未放進初值就去存取的話,會發生錯誤,要養成初始化的好習慣。 Integer[] anArray = new Integer[5]; for(int i = 0; i < anArray.length; i++){ // 錯誤:會有執行時期錯誤 System.out.println(anArray[i]); }

  27. x[0][0] x[0][1] x[0][2] x[0][3] x[0][4] x[1][0] x[1][1] x[1][2] x[1][3] x[1][4] 陣列(Array) • 多維陣列 • 與一維陣列宣告方式相同,以 [] 數目代表維度 • 例:int[][] xxx = new int[2][3]; //2*3 array int[][][] xxx = new int[2][2][2]; //2*2*2 • 多維陣列其實就是陣列中的陣列 • 多維陣列宣告 • int[][] x = new int[2][5]; int x[2][5]

  28. 陣列(Array) • 多維陣列的初始化 • 多維陣列也可以如一維陣列般,一邊宣告一邊給初值: String[][] Month = {{"January", "31"}, {"February", "28"}, {"March", "31"}, {"April", "30"}, {"May", "31"}, {"June", "30"}, {"July", "31"}, {"August", "31"}, {"September", "30"}, {"October", "31"}, {"November", "30"}, {"December", "31"}};

  29. 陣列(Array) • Example: ArrayOfArraysDemo.java public class ArrayOfArraysDemo { public static void main (String[] args) { int month = Integer.parseInt(args[0]); String[][] Month ={{"January", "31"}, {“February", "28"}, {"March", "31"}, {"April", "30"}, {"May", "31"}, {"June", "30"}, {"July", "31"}, {"August", "31"}, {"September", "30"}, {"October", "31"}, {"November", "30"}, {"December", "31"}}; System.out.println(Month[month-1][0] + " has " + Month[month-1][1] + " days" ); } }

  30. 陣列(Array) • 複製陣列 • 使用 System 的類別方法 arraycopy() • arraycopy 需要五個參數 public static void arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length)

  31. 陣列(Array) • Example: ArrayCopyDemo.java char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7);

  32. Your Turn • Basic Practice • 建立了 a, b, c 均為 3 列 3 行(3x3)的矩陣(Matrix),且將 a和 b 矩陣的加總存放在 c 矩陣裡,並且將結果顯示在螢幕上。 • a, b 中的數字請用亂數產生(介於 0 ~ 20 之間) • Advanced Practice • 費氏數列 (Fibonacci) • 1, 1, 2, 3, 5, 8, 13, … • 利用迴圈和陣列,求出第 50 項,fib[i]=fib[i-1]+fib[i-2]

  33. 基本型態字元(char) • 基本型態字元(char)定義: • 字元為顯示電腦符號之基本單位 • char a = ‘a’; • char b = ‘1’; • 字元在 Java 與 C++ 中的不同 • 在C/C++裡,char是一個 8 位元 的型態 • 在 Java 中,char是一個16 位元 的型態 • 全球文字碼 (Unicode)完整地定義了世界的字元集,已呈現在所有人類語言中找到的字元。它統一了多種字元集,像是拉丁語、希臘語、阿拉伯語、斯拉夫語、希伯來語、日語的片假名,韓語以及其他更多的語言。

  34. 基本型態字元(char) • ASCII Table • 每個字元在電腦裡皆有唯一對應的代碼. • 一個公定的字元對應標準為 American Standard Code for Information Interchange (ASCII). • printable characters have • codes from 32 to 126 • control characters. • others • 例如:數字 0 ~ 9,在 ASCII 中對應的碼為 48~57

  35. 基本型態字元(char) • Example: Showchar.java import java.io.*; public class Showchar { public static void main(String args[]) throws IOException { int x = System.in.read(); System.out.println(x); System.out.println((char)(x-32)); } }

  36. 字元(Character) • 字元物件 – Character Object • Java 提供了兩種處理字元的方法 • char chr = ‘a’; • Character charObj = new Character(‘a’); • 特性比較

  37. 字元(Character) • Character 建構元(Constructor) • Character(char); • 如:Character charObj = new Character(‘a’); • Character 唯一的建構元,根據參數傳來的字元,建立一個 Character 物件 • 一旦 Character 物件建好後,就不得更改內涵的字元資料

  38. 字元(Character) • 提供的測試方法

  39. 字元(Character) • 提供的轉換方法(Casting Method) • 例如: • Character charObj = new Character(‘a’); • 轉成字元:char x = charObj.charValue(); • 轉成字串:String s = charObj.toString(); • 相關用法及其他 methods 請查閱 J2SE 1.4.2 API

  40. 字元(Character) • Example: CharacterDemo.java Character a = new Character('a'); Character a2 = new Character('a'); Character b = new Character('b'); int difference = a.compareTo(b); if (difference == 0) { System.out.println("a is equal to b."); } else if (difference < 0) { System.out.println("a is less than b."); } else if (difference > 0) { System.out.println("a is greater than b."); } System.out.println("a is " + ((a.equals(a2)) ? "equal" : "not equal") + " to a2."); System.out.println("The character " + a.toString() + " is " + (Character.isUpperCase(a.charValue()) ? "upper" : "lower") + "case.");

  41. 字串(String) • String 物件 • 專門處理字串的常數 • 如:在 Java 程式中出現 “Hello! World!”,Java 即以 String 物件處理之 • 特性:一旦宣告後,其內容不可更動 • StringBuffer 物件 • 專門處理字串的變數 • 如:在 Java 中出現 “Hello!” + “World!” 這類運算時,Java 會偷偷以 StringBuffer 處理 • 特性:字串內容可以做更動

  42. 字串(String) • 建立字串 • String s = “”; // 產生一個空字串物件 • String s = new String(); • String s = “We are studying Java!!”; • String s = new String(“We are studying Java!!”); // NO!!

  43. 字串(String) • 常用的字串建構元(Constructors) • String() – 建立空字串 • String(byte []) -- 利用給定的位元陣列來產生字串物件 String(byte [], int, int) • String(char []) -- 利用給定的 char 陣列來產生字串物件 String(char[], int, int) • String(String) -- 給定一個字串,來建立一個新的字串 • String(StringBuffer) – 給定一個字串緩衝來建立一個字串物件

  44. 字串(String) • 取得字串的長度 • 利用字串提供的 length() 方法 • 範例: String s = “Hello! World!”;System.out.println(s.length()); 結果:13

  45. 字串(String) • charAt(int) • 呼叫 charAt(int),來取得字串的某個字元 • 第一個字的 index 是 0,最後一個字元是 length()-1 • 例如: String str = “Niagara. O roar again!”; char aChar = str.charAt(9); 此時 aChar 的字元內容為 ‘O’

  46. 字串(String) • 利用 substring() 方法來取得子字串 • String substring(int beginIndex); • String substring(int beginIndex, int endIndex); • 例如: String str = “Niagara. O roar again!” String roar = str.substring(11, 15); 此時 roar 字串內容為 “roar”

  47. 字串(String) • 尋找字串中的字元或子字串 • 利用 indexOf() 與 lastIndexOf() 方法 • indexOf(): 從第一個字元往後找 • lastIndexOf(): 從最後一個字元往前找 • 提供的方法 • int indexOf(String str); • 回傳字串中,某特定子字串 str 第一次出現的位置 • int lastIndexOf(String str); • 回傳字串中,某特定子字串 str 最後一次出現的位置

  48. 字串(String) • Example: StringDemo.java String s = "This is a book"; System.out.println("String: " + s); System.out.println("substring(8): " + s.substring(8)); System.out.println("substring(0, 6): " + s.substring(0, 6)); System.out.println("charAt(8): " + s.charAt(8)); System.out.println("indexOf('i'): " + s.indexOf('i')); System.out.println("indexOf(\"is\"): " + s.indexOf("is")); System.out.println("lastIndexOf('i'): " + s.lastIndexOf('i')); System.out.println("lastIndexOf(\"is\"): " + s.lastIndexOf("is")); System.out.println("startsWith(\"Th\"): " + s.startsWith("Th")); System.out.println("endsWith(\"ok\"): " + s.endsWith("ok"));

  49. 字串(String) • 字串比較 • 範例: • 結果:a != b • 因為 == 在 Java 字串中,比較的是位址,不是內容 • String a = “Java”; • String b = “Ja”;b = b + “va”; // 此時 b = “Java”if (a == b) System.out.println (“a == b”);else System.out.println (“a != b”);

  50. 字串(String) • 字串比較 • 比較字串內容要用 String 物件本身提供的一個方法,叫做 equals() • 範例 • 結果:a==b • String a = “Java”String b = “Ja”;b = b + “va”; //此時 b = “Java”if (a.equals(b)) System.out.println (“a == b”);else System.out.println (“a != b”);

More Related