Using objects: String, Math, and wrappers · Sử dụng objects: String, Math, và wrappers
Using objects
- An object is a value that knows how to do things. You call its methods with a dot
.. - A
Stringis an object.Math,Integer, andDoublegive you ready-made tools. - In this lesson you learn to make objects and use their methods.
Sử dụng đối tượng
- Một đối tượng là một giá trị biết cách làm những việc gì đó. Bạn gọi các phương thức của nó với dấu chấm
.. - Một
Stringlà một đối tượng.Math,Integer, vàDoublecung cấp cho bạn các công cụ sẵn sàng. - Trong bài học này, bạn học cách tạo đối tượng và sử dụng các phương thức của chúng.
Making objects with new
- Some objects are made with the keyword
newand a constructor. - A
Stringis special: you can write it directly with quotes, like"hi". - You can also make a separate
Stringobject withnew String("..."), but quotes are the normal way.
Tạo đối tượng với new
- Một số đối tượng được tạo với từ khóa
newvà một constructor. - Một
Stringlà đặc biệt: bạn có thể viết nó trực tiếp với dấu ngoặc kép, như"hi". - Bạn cũng có thể tạo một đối tượng
Stringriêng biệt vớinew String("..."), nhưng dấu ngoặc kép là cách thông thường.
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
String copy = new String("Hello");
System.out.println(greeting);
System.out.println(copy);
}
}
String methods
s.length()— how many characters are ins.s.charAt(i)— the character at positioni(the first position is 0).s.substring(a, b)— the part fromaup to but not includingb.s.indexOf("x")— the first position of"x", or-1if not found.
Các phương thức String
s.length()— bao nhiêu ký tự có trongs.s.charAt(i)— ký tự tại vị tríi(vị trí đầu tiên là 0).s.substring(a, b)— phần từalên đến nhưng không bao gồmb.s.indexOf("x")— vị trí đầu tiên của"x", hoặc-1nếu không tìm thấy.
public class Main {
public static void main(String[] args) {
String word = "computer";
System.out.println(word.length()); // 8
System.out.println(word.charAt(0)); // c
System.out.println(word.substring(0, 4)); // comp
System.out.println(word.indexOf("put")); // 3
}
}
Comparing Strings
- Use
s.equals(other)to check if two Strings have the same letters. - Do not use
==to compare Strings — it can give the wrong answer. We learn why in lesson 3. s.compareTo(other)returns0when equal, a negative number ifscomes first in order, and a positive number if it comes later.
So sánh String
- Sử dụng
s.equals(other)để kiểm tra xem hai String có các chữ cái giống nhau hay không. - Không sử dụng
==để so sánh String — nó có thể đưa ra câu trả lời sai. Chúng ta sẽ học lý do tại sao trong bài 3. s.compareTo(other)trả về0khi bằng nhau, một số âm nếusxuất hiện trước theo thứ tự, và một số dương nếu nó xuất hiện sau.
public class Main {
public static void main(String[] args) {
String a = "cat";
String b = "cat";
String c = "dog";
System.out.println(a.equals(b)); // true
System.out.println(a.equals(c)); // false
System.out.println(a.compareTo(c)); // negative: "cat" is before "dog"
}
}
Math methods
Mathholds math tools. You call them onMathitself, likeMath.abs(-5).Math.abs(x)— the size ofxwith no minus sign.Math.pow(b, e)—bto the powere(returns adouble).Math.sqrt(x)— the square root ofx(returns adouble).Math.random()— a randomdoublefrom0.0up to (not including)1.0.
Các phương thức toán học
Mathchứa các công cụ toán học. Bạn gọi chúng trên chínhMath, nhưMath.abs(-5).Math.abs(x)— kích thước củaxkhông có dấu trừ.Math.pow(b, e)—bmũe(trả về mộtdouble).Math.sqrt(x)— căn bậc hai củax(trả về mộtdouble).Math.random()— một số ngẫu nhiêndoubletừ0.0lên đến (không bao gồm)1.0.
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-7)); // 7
System.out.println(Math.pow(2, 3)); // 8.0
System.out.println(Math.sqrt(9)); // 3.0
// Math.random() changes each run, so we do not print it here.
}
}
Wrappers and autoboxing
intanddoubleare simple types. Their object versions areIntegerandDouble.- Java can switch between them for you. This is called autoboxing.
Integer.parseInt("42")turns text into anint.Double.parseDouble("3.5")turns text into adouble.
Wrapper và autoboxing
intvàdoublelà các kiểu đơn giản. Các phiên bản đối tượng của chúng làIntegervàDouble.- Java có thể chuyển đổi giữa chúng cho bạn. Điều này được gọi là autoboxing (tự đóng hộp).
Integer.parseInt("42")biến văn bản thành mộtint.Double.parseDouble("3.5")biến văn bản thành mộtdouble.
public class Main {
public static void main(String[] args) {
Integer boxed = 10; // int -> Integer (autoboxing)
int back = boxed; // Integer -> int (unboxing)
int n = Integer.parseInt("42");
double d = Double.parseDouble("3.5");
System.out.println(back + n); // 52
System.out.println(d); // 3.5
}
}
Common mistakes
- Compare Strings (and other objects) with
.equals(), not==. Math.random()returns a value from0up to (but not including)1.
Lỗi thường gặp
- So sánh Strings (và các đối tượng khác) với
.equals(), không phải==. Math.random()trả về một giá trị từ0đến (nhưng không bao gồm)1.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Bây giờ bạn thử
- Mỗi nhiệm vụ điền sẵn khung lớp — viết mã của bạn bên trong main, hoặc hoàn thành phương thức được hiển thị.
- Nhấn Chạy để biên dịch và chạy, sau đó Kiểm tra câu trả lời.
- Mã của bạn được biên dịch và chạy trên máy chủ, vì vậy ngay cả lần chạy đầu tiên cũng rất nhanh.
The String word is "programming". Print its length on the first line, then print the first 4 letters (use substring(0, 4)) on the second line. · String ⟨word⟩ có giá trị là ⟨"programming"⟩. In độ dài của nó trên dòng đầu tiên, sau đó in 4 ký tự đầu tiên (sử dụng ⟨substring(0, 4)⟩) trên dòng thứ hai.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete hypotenuse(double a, double b) so it returns the length of the longest side of a right triangle: the square root of a*a + b*b. Use Math.sqrt and Math.pow (or a*a). · Hoàn thiện ⟨hypotenuse(double a, double b)⟩ sao cho trả về độ dài cạnh dài nhất của tam giác vuông: căn bậc hai của ⟨a*a + b*b⟩. Sử dụng ⟨Math.sqrt⟩ và ⟨Math.pow⟩ (hoặc ⟨a*a⟩).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete sameWord(String a, String b) so it returns true when the two Strings have the same letters, and false otherwise. Use .equals (not ==). · Hoàn thiện ⟨sameWord(String a, String b)⟩ sao cho trả về ⟨true⟩ khi hai Strings có cùng các chữ cái, và ⟨false⟩ ngược lại. Sử dụng ⟨.equals⟩ (không dùng ⟨==⟩).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.