Cấu trúc dữ liệu v Trong nhiều bài toán, một số dữ liệu có cấu trúc tự nhiên § Ví dụ : Texts are sequences of characters Images are matrices of pixels Classes contain sets of s
Trang 1BÀI 3: MẢNG VÀ XÂU
PHẦN 1:
NGÔN NGỮ JAVA
Trang 2Mảng
Trang 3Cấu trúc dữ liệu
v Trong nhiều bài toán, một số dữ liệu có cấu trúc
tự nhiên
§ Ví dụ :
Texts are sequences of characters
Images are matrices of pixels
Classes contain sets of students
v Java cung cấp một số lớp và tool gọi là cấu trúc
dữ liệu
§ hỗ trợ tổ chức dữ liệu
§ thuận lợi trong việc truy cập và cập nhập dữ liệu
Trang 5Opening problem
v Xét chương trình sau :
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average
Trang 6What makes the problem hard?
v Không sử dụng biến, cần 2 lần nhập giá trị vào
v Sử dụng biến
§ Cần khai báo bao nhiêu biến để chứa?
v Cần một cách -> khai báo nhiều biến một lần
Trang 7Mảng
v array: Đối tượng chứa nhiều giá trị cùng loại
§ element: một giá trị trong mảng
§ index: số nguyên chỉ vị trí của giá trị trong mảng
3
72
84 -6
17
5
26 -2
element 0 element 4 element 9
Trang 8Khai báo mảng
v Khai báo/khởi tạo mảng :
<type>[] <name> = new <type>[<length>];
Trang 10Ví dụ
v Mảng double
v Mảng booleans
0.0 0.0
0.0 0.0
3
2
1
0 index
Trang 13Vượt quá giới hạn mảng
v Đọc/ghi index bên ngoài khoảng rộng của mảng dẫn tới một ArrayIndexOutOfBoundsException
Trang 19Bài toán nhiệt độ
v Solve the following problem:
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average
Trang 20Solution
// This program reads several days' temperatures from the user
// and computes the average and how many days were above average
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
double average = (double) sum / days;
int count = 0; // see if each day is above average for (int i = 0; i < days; i++) {
if (temperatures[i] > average) {
count++;
}
Trang 21Ưu điểm của mảng
v Arrays store a large amount of data accessible from one variable
v Arrays let us access data in random order
v Arrays can represent sequential data
§ An array of quiz scores can store not just the scores, but also the order in which the quizzes were taken
Trang 22Câu lệnh khởi tạo mảng
v Khởi tạo nhanh :
<type>[] <name> = {<value>, <value>, ,
<value>};
v Ví dụ:
int[] numbers = { 12, 49, -2, 26, 5, 17, -6 };
Trang 25Dịch chuyển các phần
tử trong mảng
Trang 27Chèn phần tử
public static void insertInOrder(int[] array, int num) {
int insertionIndex = findInsertionIndex(array, num);
public static int findInsertionIndex(int[] array, int num) {
for (int i = 0; i < array.length; i++) {
Trang 282 3 4
1
0 index
Trang 29Quay trái phần tử
public static void rotateLeft(int[] array) {
int first = array[0];
for (int i = 0; i < array.length - 1; i++) { array[i] = array[i + 1];
}
array[array.length - 1] = first;
}
Trang 32Mảng nhiều chiều
Trang 3335
Chứa giá trị của một bảng ?
8 sinh viên có 10 điểm thi :
Trang 34Solution 1: 1 sinh viên/mảng
double [] student1 = new double[10];
Trang 38Mảng 2 chiều không đều
double [][] quizScores = new double[4][];
quizScores[0] = new double[3];
quizScores[2] = new double[5];
quizScores
quizScores[0]
quizScores[1]
Trang 39Xử lý text
Trang 40Xử lý text
v text processing: Duyệt, sửa, định dạng
§ Text processing thường sử dụng vòng lặp for để duyệt từng ký tự của xâu
Biểu diễn một ký tự riêng lẻ Biểu điễn chuổi ký tự
Dữ liệu kiểu gốc Kiểu đối tượng; không phải kiểu gốc
Sử dụng dấu nháy đơn ' Sử dụng dấu nháy kép
Trang 41Characters
v char: Kiểu dữ liệu gốc, biểu diễn một ký tự đơn lẻ
Trang 42Strings
v String: Kiểu đối tượng biểu diễn chuỗi ký tự
§ Length: 0, 1 hoặc dài hơn
§ Mỗi phần tử: char
§ "string"
§ Khai báo, khởi tạo, gán và sử dụng biến String như dữ liệu khác
String s = “Hello, world\n”; // declare, init System.out.println(s); // use value
s = s + “I am your master\n”; // concatenate
Trang 43Các phương thức của String
Các kiểu đối tượng có thể có các phương thức <> kiểu dữ liệu gốc
returns the index where the start of the given string appears in this string (-1 if not found)
returns the characters in this string from
index1 up to, but not including, index2
Trang 45Gọi các phương thức của String
v Giả sử s biến kiểu String
v Cú pháp:
s.<method>(<args>)
v Some examples:
String s = “Cola”;
int len = s.length(); // len == 4
char firstLetter = s.charAt(0); // ‘C’
int index = s.indexOf(“ol”); // index == 1 String sub = s.substring(1,3); // “ol”
String up = s.toUpperCase(); // “COLA”
Trang 46Fun with char !
Trang 47char vs String
v 'h' is a char
char c = 'h';
§ char : kiểu dữ liệu gốc -> không có phương thức
§ Không được gọi: c.length() or c.toUpperCase()
v "h" is a String
String s = "h";
§ Đói tượng -> có phương thức
Trang 48Numbers vs Strings
v 345 is an int
int i = 345;
§ int values are primitive; you cannot call methods on them
§ CAN perform arithmetic: i = i * 2; // i==690
§ CANNOT say i.length() or i.charAt(0)
v “345" is a String
String s = “345";
§ Strings are objects; they contain methods that can be called
Trang 49So sánh string
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
Trang 50So sánh strings
dụng trong điều kiện <test>
whether this string’s beginning matches
Trang 52Chuyển đổi kiểu dữ liệu
int x = 2640;
int y = 5280;
return x / y; // integer arithmetic
double z = (double) x;
Trang 55Ép kiểu với String?
Ép kiểu (String) không sử dụng được với các kiểu dữ liệu gốc như char, int, vàdouble
Có nhiều cách để ép kiểu String:
Trang 56Ép kiểu với String?
Ép kiểu (String) không sử dụng được với các kiểu dữ liệu gốc như char, int, vàdouble
Có nhiều cách để ép kiểu String:
Converting from strings:
String s to int: Integer.parseInt(x)
String s to double:
Trang 57Name 1 has 9 letters
Name 2 has 6 letters
Name 3 has 5 letters
Trang 58Solution
import java.util.Scanner;
public class NameLength {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
System.out.print(“Please enter your name”);
Trang 59Lớp Scanner (tiếp)
int nextInt() Reads the next token, converts it to an int (if
possible), and returns the int value
double nextDouble() Reads the next token, converts it to a double (if
possible), and returns the double value
String next() Reads the next token, and returns it
boolean hasNext() Returns true if there are more tokens
Trang 60StringBuilder /StringBuffer
v Một lựa chọn khác cho lớp String
v StringBuilder/StringBuffer is more flexible than String You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created
Trang 61v Mềm dẻo hơn String
<> String: đối tượng được cố định khi được tạo
v Thường phân tách StringBuilder thành String khi hoàn thành khởi tạo
Trang 62StringBuilder Constructors
Trang 63Modifying Strings in the Builder
Trang 64toString, capacity, length, setLength, và charAt
Trang 65Ví dụ
StringBuilder stringBuilder = new StringBuilder("Welcome to ");
stringBuilder.append("Java");
stringBuilder.delete(8, 11) changes the builder to Welcome Java
stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java stringBuilder.reverse() changes the builder to avaJ ot emocleW
stringBuilder.replace(11, 15, "HTML")
changes the builder to Welcome to HTML
stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java