Using objects: String, Math, and wrappers · 使用对象:String、Math 和包装类
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.
使用对象
- 对象(object)是一个会做事情的值。你用点号
.来调用它的方法(method)。 String就是一个对象。Math、Integer和Double给你现成的工具。- 在这节课里,你学习如何创建对象并使用它们的方法。
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.
用 new 创建对象
- 有些对象用关键字
new和一个构造器(constructor)来创建。 String很特别:你可以直接用引号写它,例如"hi"。- 你也可以用
new String("...")创建一个独立的String对象,但用引号是常见的写法。
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.
String 的方法
s.length()——s里有多少个字符。s.charAt(i)—— 位置i上的字符(第一个位置是 0)。s.substring(a, b)—— 从a开始到b(不包括b)的那一部分。s.indexOf("x")——"x"第一次出现的位置,找不到就返回-1。
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.
比较字符串
- 用
s.equals(other)来检查两个字符串是否有相同的字母。 - 不要用
==来比较字符串 —— 它可能给出错误的答案。我们在第 3 课学习原因。 s.compareTo(other)相等时返回0,如果s在顺序上更靠前就返回负数,更靠后就返回正数。
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.
Math 的方法
Math装着数学工具。你在Math本身上调用它们,例如Math.abs(-5)。Math.abs(x)——x去掉负号后的大小。Math.pow(b, e)——b的e次方(返回一个double)。Math.sqrt(x)——x的平方根(返回一个double)。Math.random()—— 一个从0.0到1.0(不包括1.0)的随机double。
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.
包装类与自动装箱
int和double是简单类型。它们的对象版本是Integer和Double。- Java 可以替你在两者之间转换。这叫作自动装箱(autoboxing)。
Integer.parseInt("42")把文字变成int。Double.parseDouble("3.5")把文字变成double。
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.
常见错误
- 比较字符串(和其他对象)用
.equals(),不是==。 Math.random()返回0到1之间(不含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.
现在轮到你
- 每个任务都已经填好了类的骨架 —— 把你的代码写在 main 里面,或者补全给出的方法。
- 按运行来编译并运行,然后按检查答案。
- 你的代码在服务器上编译并运行,所以第一次运行也很快。
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. · 字符串 word 是 "programming"。第一行打印它的长度,第二行打印前 4 个字母(用 substring(0, 4))。
Click Run to see the output here. · 点击“运行”查看此处输出。
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). · 完成 hypotenuse(double a, double b),让它返回直角三角形最长边的长度:a*a + b*b 的平方根。使用 Math.sqrt 和 Math.pow(或 a*a)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete sameWord(String a, String b) so it returns true when the two Strings have the same letters, and false otherwise. Use .equals (not ==). · 完成 sameWord(String a, String b),当两个字符串有相同的字母时返回 true,否则返回 false。使用 .equals(不要用 ==)。
Click Run to see the output here. · 点击“运行”查看此处输出。