1 / 29

CS@KKU Java Summer Camp 2011

CS@KKU Java Summer Camp 2011. Day 1 - 3 เรื่อง Array. Introduction. Arrays are commonly used efficient data structures. They allow us to group data together in an efficient manner. . ปัญหา. ถ้าต้องเก็บข้อมูลสถิติความถี่ของคะแนนของนักเรียน มีคนได้แต่ล่ะคะแนนกี่คน เช่น

savanna
Télécharger la présentation

CS@KKU Java Summer Camp 2011

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. CS@KKU Java Summer Camp 2011 Day 1 - 3 เรื่อง Array โดย วชิราวุธ ธรรมวิเศษ

  2. Introduction • Arrays are commonly used efficient data structures. • They allow us to group data together in an efficient manner. 

  3. ปัญหา • ถ้าต้องเก็บข้อมูลสถิติความถี่ของคะแนนของนักเรียน มีคนได้แต่ล่ะคะแนนกี่คน เช่น • 100 คะแนน 1 คน • 99 คะแนน 0 คน • 98 คะแนน 5 คน • … • 0 คะแนน 1 คน

  4. การแก้ปัญหา • เรา อาจจะต้องสร้างตัวแปร counter จำนวน 100 ตัวเพื่อใช้นับจำนวนของแต่ละคะแนน int    counter1, counter2, counter3, ....., counter10; int    counter11, counter12, counter13, ..., counter20; int    counter21, counter22, counter23, ....., counter30;            ......... int    counter91, counter92, counter93, ..., counter100; int    percentage;

  5. การแก้ปัญหา • การเขียนโปรแกรม ก็ต้องเขียนแบบนี้ for (int i=0; i<numStudentsInClass; i++) {         // รับค่าคะแนนจากผู้ใช้        percentage = Keyboard.getInteger();         // เงื่อนไขการนับ        switch(percentage) {             case 1:    counter1++; break;             case 2:    counter2++; break;             case 3:    counter3++; break;             ......             case 100:    counter100++; break;         }     }

  6. การแก้ปัญหา • จากตัวอย่างโปรแกรม คงจะพอมองเห็นปัญหาแล้วว่าการจัดการตัวแปรแบบนี้ คงเหนื่อยในการเขียนโปรแกรม • Array จึงเข้ามาช่วย จัดการปัญหาตรงจุดนี้ An Array is a bounded (fixed size) collection of elements of the same type.

  7. คุณสมบัติของ Array ของ Java • indexedคือสามารถเข้าถึงสมาชิก (Element) แต่ละตัวได้โดยอาศัย index หรือ ดัชนี ซึ่งจะเป็นตัวเลขมี 0 เป็นค่าเริ่มต้น • fixed sizeเมื่อสร้าง array แล้ว จะไม่สามารถเพิ่ม หรือ ลบ สมาชิก • strongly typed and homogeneous นั่นคือสมาชิกทุกตัวต้องมีชนิดข้อมูลเดียวกัน • bounds-checkedถ้าเราพยายาม access สมาชิกที่เกินขนาดของ array แล้ว java จะหยุดคำสั่งนั้น

  8. Arrays • Unlike many other data structures, access to array elements is immediate since they are stored in contiguous (i.e., side by side) memory locations.

  9. การประกาศตัวแปรแบบ array • Variables that hold arrays are declared using square brackets []. • The brackets may appear either with the variable’s type: • int [] data; • or with the variable's name: • int data[];

  10. การสร้าง Array • Array ถือว่าเป็น class ชนิดหนึ่ง • การสร้าง array จะใช้คำสั่ง new เหมือนการสร้าง object แต่ใช้เครื่องหมาย [ ] ระบุขนาด • int x[]; • x = new int[100]; • ต้องระบุขนาดของ array ด้วยและเมื่อ array ถูก new แล้ว เราจะไม่สามารถเปลี่ยนขนาดของ array ได้อีก

  11. การสร้าง Array • Just like any other variables, both declaration and creation can occur on the same line: int x[] = new int[100]; int[]      sickDays = new int[30]; Person[]   friends = new Person[50];

  12. ค่าเริ่มต้นของ elements เมื่อสร้าง array ใหม่ ข้อมูลภาย array จะยังไม่มี ดังนั้นjava จึงกำหนดค่า default เป็นค่าเริ่มต้นของ elements แต่ละชนิด • ตัวเลข = 0 • boolean = false • reference = null • character = null

  13. ค่าเริ่มต้นของ elements • When you create an array of reference types, only the array itself is created.  • The array is NOT initialized with new objects in each location.

  14. การกำหนดค่าให้ elements • เหมือนตัวแปรปกติ แต่เพิ่ม [index] int[] ages = new int[3]; // valid indices are 0,1 & 2 ages[0] = 34; ages[1] = 12; ages[2] = 45; ข้อควรระวัง การ access เกินขนาดของ array ages[3] = 29; // ERROR: 3 is an invalid index

  15. การกำหนดค่าให้ elements พร้อมๆกัน • ใช้เครื่องหมายปีกกา • ไม่ต้องใช้ new int[] ages = {34, 12, 45}; double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5}; boolean[] tired = {true, false, false, true}; String[] names = {"Bill","Jennifer","Joe"}; char vowels[] = {'a', 'e', 'i', 'o', 'u'};

  16. การกำหนดค่าให้ elements พร้อมๆกัน • ใช้เครื่องหมายปีกกา BankAccount[] accounts = {     new BankAccount("Fred", 100.00),     new BankAccount("Biff", 2380.00),     new BankAccount("Martha", 500.00),     new BankAccount("Jim", 175.56),     new BankAccount("Betty", 924.02) };

  17. Array of objects: • Always be careful when accessing an arrays of objects: • ตัวอย่างนี้ customers[0] จะมีค่าเป็น null • การเรียก customers[0].getName() จึงเกิด error Customer[]  customers = new Customer[1000]; System.out.println(customers[0].getName());

  18. Array of objects: • Make sure to assign values to the array BEFORE trying to use them: Customer[]  customers = new Customer[1000]; customers[0] = new Customer("Jim"); System.out.println(customers[0].getName());

  19. ขนาดของ Array • เราสามารถทราบขนาดของ array ด้วยการเรียกใช้ ตัวแปร length • ตัวแปร length ของ array ไม่สามารถเปลี่ยนค่าได้ double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5};String[] names = {"Bill","Jennifer","Joe"}; System.out.println(heights.length);     // prints 5 System.out.println(names.length);       // prints 3 names[1] = null;                        // erases JenniferSystem.out.println(names.length);       // still prints 3

  20. การแก้ปัญหาด้วย Array • จากปัญหาการหาความถี่คะแนน สามารถใช้ array ได้ดังนี้ int    counter[] = newint[101]; int    percentage; for (int i=0; i<numStudentsInClass; i++) {   // Get the percentage from the user     percentage = Keyboard.getInteger();     // Now update the appropriate counter     counter[percentage]++; }

  21. ตัวอย่าง การหาค่าเฉลี่ย publicclass Calculator {     public static double calculateAverage(int[] numbers) {         int sum = 0;         for (int i=0; i<numbers.length; i++)             sum += numbers[i];         return sum/(double)numbers.length;     } } publicclass CalculatorTester { public staticvoid main(String args[]) {         int numbers[] = {23, 54, 88, 98, 23, 54, 7, 72, 35, 22};         System.out.println("The average is " + Calculator.calculateAverage(numbers));     } }

  22. การส่งตัวแปร Array เป็น parameter • Notice that when passing an array as a parameter, we DO NOT use the square brackets: Calculator.calculateAverage(numbers[]) • we DO NOT specify the type either: Calculator.calculateAverage(int numbers[])

  23. ตัวอย่าง : หาค่า maximum • Given an array of 10 numbers, how do we find the maximum ? int numbers[] = {23, 54, 88, 98, 23, 54, 7, 72, 35, 22}; int max = -999999; for (int i=0; i<numbers.length; i++) {     if (numbers[i] > max)         max = numbers[i]; } System.out.println("The maximum is " + max);

  24. Multi-Dimensional Arrays (Tables) • การใช้งาน array ที่มีหลายมิติ • 2 มิติ หรือ มากกว่า ที่ใช้มากจะเป็น 2 มิติ • Array แบบ 2 มิติใช้เพื่อ แทนข้อมูล • ตาราง • รูปภาพ (image) • Grid • แผนที่ • ฯลฯ

  25. รูปแบบการเขียน ชนิดข้อมูล tableName[][] = newtypeOrObject[rowLimit][columnLimit]; ชนิดข้อมูล tableName[][] = {{row1Data}, {row2Data}, ..., {lastRowData}}; int myTable[][] = newint[4][3];

  26. การเข้าถึง element • To access elements of the table, we merely index it by the row and the column of the element. int myTable[][] = newint[4][3]; myTable[0][0] = 34; myTable[0][1] = 15; myTable[1][3] = 26;

  27. ตัวอย่าง int myTable[][] = {{23, 45, 65, 34, 21, 67, 78},                    {46, 14, 18, 46, 98, 63, 88},                    {98, 81, 64, 90, 21, 14, 23},                    {54, 43, 55, 76, 22, 43, 33}};

  28. ตัวอย่าง : เขียนคำสั่งแสดง int myTable[][] = {{23, 45, 65, 34, 21, 67, 78},                    {46, 14, 18, 46, 98, 63, 88},                    {98, 81, 64, 90, 21, 14, 23},                    {54, 43, 55, 76, 22, 43, 33}}; for (int row=0;row<4; row++) {     for (int col=0;col<7; col++)         System.out.print(myTable[row][col] + "  ");     System.out.println(); }

  29. Array แบบ 3 มิติ • int cube[][][] = new int[3][3][3]; • ใช้เก็บข้อมูลแบบ 3 มิติ • แผนที่

More Related