跳到主要内容

使用对象与方法

AP 计算机科学 A · 第 1 主题

训练
讲义 词汇表
1.1

算法、编程与编译器导论

大纲
Learning ObjectiveEssential Knowledge

1.1.A
Represent patterns and algorithms found in everyday life using written language or diagrams.

  • 1.1.A.1 Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
  • 1.1.A.2 Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.

1.1.B
Explain the code compilation and execution process.

  • 1.1.B.1 Code can be written in any text editor; however, an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
  • 1.1.B.2 A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.

1.1.C
Identify types of programming errors.

  • 1.1.C.1 A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
  • 1.1.C.2 A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
  • 1.1.C.3 A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
  • 1.1.C.4 An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program's execution.

来源:美国大学理事会 AP 课程与考试说明

一个算法(algorithm)是一个解决一个问题的有限的、逐步的程序。一个程序(program)用一门计算机能运行的语言表达一个算法。Java 是编译(compiled)的:编译器(compiler)把你的源代码翻译成字节码(bytecode),它由 Java 虚拟机(JVM)(Java Virtual Machine)运行。一个语法错误(syntax error)(破坏语法)被编译器捕捉;一个逻辑错误(logic error)(错误的结果)不被——程序运行但行为不当。

一个编译器一次翻译整个程序;一个解释器逐行运行它
一个编译器一次翻译整个程序;一个解释器逐行运行它
词汇表 训练
英文 中文 拼音
algorithm 算法 suàn fǎ
program 程序 chéng xù
compiled 编译 biān yì
compiler 编译器 biān yì qì
syntax error 语法错误 yǔ fǎ cuò wù
logic error 逻辑错误 luó jí cuò wù
1.2

变量与数据类型

大纲
Learning ObjectiveEssential Knowledge

1.2.A
Identify the most appropriate data type category for a particular specification.

  • 1.2.A.1 A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
  • 1.2.A.2 The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
  • 1.2.A.3 A reference type is used to define objects that are not primitive types.

1.2.B
Develop code to declare variables to store numbers and Boolean values.

  • 1.2.B.1 The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.
    • Exclusion statement: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam.
  • 1.2.B.2 A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.

来源:美国大学理事会 AP 课程与考试说明

一个变量(variable)是一个存储一个固定类型(type)的值的命名的盒子。Java 的主要基本类型(primitive types)是 int(整数)、double(小数)和 boolean(true/false)。类型在先地声明:

Java 的基本数据类型,每个存储一种不同的值
Java 的基本数据类型,每个存储一种不同的值
int score = 90;
double price = 4.99;
boolean passed = true;
探索

Explore how a variable holds one value at a time

A variable is a named box that stores one value of a fixed type. Step through the lines and watch each box take its value; notice that reassigning score overwrites the old number rather than making a new box.

词汇表 训练
英文 中文 拼音
variable 变量 biàn liàng
type 类型 lèi xíng
primitive types 基本类型 jī běn lèi xíng
1.3

表达式与输出

大纲
Learning ObjectiveEssential Knowledge

1.3.A
Develop code to generate output and determine the result that would be displayed.

  • 1.3.A.1 System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.

1.3.B
Develop code to utilize string literals and determine the result of using string literals.

  • 1.3.B.1 A literal is the code representation of a fixed value.
  • 1.3.B.2 A string literal is a sequence of characters enclosed in double quotes.
  • 1.3.B.3 Escape sequences are special sequences of characters that can be included in a string. They start with a \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline \n.

1.3.C
Develop code for arithmetic expressions and determine the result of these expressions.

  • 1.3.C.1 Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
  • 1.3.C.2 The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value.
    • Exclusion statement: Expressions that result in special double values (e.g., infinities and NaN) are outside the scope of the AP Computer Science A course and exam.
  • 1.3.C.3 When dividing numeric values that are both int values, the result is only the integer portion of the quotient. When dividing numeric values that use at least one double value, the result is the quotient.
  • 1.3.C.4 The remainder operator % is used to compute the remainder when one number a is divided by another number b.
    • Exclusion statement: The use of values less than 0 for a and the use of values less than or equal to 0 for b is outside the scope of the AP Computer Science A course and exam.
  • 1.3.C.5 Operators can be used to construct compound expressions. At compile time, numeric values are associated with operators according to operator precedence to determine how they are grouped. Parentheses can be used to modify operator precedence. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right.
  • 1.3.C.6 An attempt to divide an integer by the integer zero will result in an ArithmeticException.
    • Exclusion statement: The use of dividing by zero when one numeric value is a double is outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

一个表达式(expression)组合值和运算符(operators)来计算一个结果:+ - * /%(取模(modulus),余数)。整数除法(integer division)截断:7 / 23,而 7 % 21运算符优先级(operator precedence)遵循数学(*/%+- 之前)。用以下打印:

System.out.print("no newline");
System.out.println("with newline");

整数除以整数 0(像 7 / 0)是不允许的,在运行时以一个 ArithmeticException 崩溃。在一个字符串里,一个反斜杠标记一个转义序列(escape sequence):\" 打印一个双引号,\\ 一个单反斜杠,而 \n 开始一个新行——所以 System.out.println("She said \"hi\""); 打印 She said "hi"

探索

Explore the order of operations step by step

Java applies *, /, % before + and -, working left to right. Watch each step and see why 2 + 3 * 4 is $14$, not $20$ — the multiplication happens first.

词汇表 训练
英文 中文 拼音
expression 表达式 biǎo dá shì
modulus 取模 qǔ mó
escape sequence 转义序列 zhuǎn yì xù liè
1.4

赋值语句与输入

大纲
Learning ObjectiveEssential Knowledge

1.4.A
Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.

  • 1.4.A.1 Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
  • 1.4.A.2 The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.
    • Exclusion statement: The use of assignment operators inside expressions (e.g., a = b = 4; or a[i += 5]) is outside the scope of the AP Computer Science A course and exam.
  • 1.4.A.3 During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression.

1.4.B
Develop code to read input.

  • 1.4.B.1 Input can come in a variety of forms, such as tactile, audio, visual, or text. The Scanner class is one way to obtain text input from the keyboard.
    • Exclusion statement: Any specific form of input from the user is outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

一个赋值(assignment)x = expr; 求右侧的值并把它存进左边的变量。用一个 Scanner 读输入:

Scanner in = new Scanner(System.in);
int age = in.nextInt();
String name = in.next();
词汇表 训练
英文 中文 拼音
assignment 赋值 fù zhí
1.5

类型转换与变量取值范围

大纲
Learning ObjectiveEssential Knowledge

1.5.A
Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.

  • 1.5.A.1 The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
  • 1.5.A.2 Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
  • 1.5.A.3 Some code causes int values to be automatically cast (widened) to double values.
  • 1.5.A.4 Values of type double can be rounded to the nearest integer by (int)(x + 0.5) for non-negative numbers or (int)(x - 0.5) for negative numbers.

1.5.B
Describe conditions when an integer expression evaluates to a value out of range.

  • 1.5.B.1 The constant Integer.MAX_VALUE holds the value of the largest possible int value. The constant Integer.MIN_VALUE holds the value of the smallest possible int value.
  • 1.5.B.2 Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.
  • 1.5.B.3 If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.

1.5.C
Describe conditions that limit accuracy of expressions.

  • 1.5.C.1 Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, use int values.
    • Exclusion statement: Other special decimal data types that can be used to avoid rounding errors are outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

int 的范围、溢出与截断

每个类型有一个固定的范围;一个 int 超过约 21 亿溢出。类型转换(casting)在类型之间转换。加宽(intdouble)是自动的;缩窄需要一个显式的转换,它截断(不舍入):

double avg = (double) total / count;   // force real division
int whole = (int) 3.9;                 // 3, truncated

考试技能: 注意整数除法在期望一个小数时产生一个截断的结果——先把一个操作数转换成 double

Worked example. 跟踪每个表达式:

  • 7 / 23(两个都是 int,所以除法截断);
  • 7.0 / 23.5(一个 double 迫使实数除法);
  • 7 % 21(余数);
  • (double) 7 / 23.5(转换比 / 结合得更紧,所以它是 7.0 / 2);
  • (double) (7 / 2)3.0(括号int 计算 7 / 2 = 3,然后加宽)。

最后两个看起来相似但不同——转换的位置决定截断是否发生。

探索

Why int and double store numbers differently

An int holds only whole numbers in a fixed range; a double stores a mantissa and an exponent, trading exactness for a huge range. Casting doubleint throws away the fraction, and a value past an int's range overflows.

词汇表 训练
英文 中文 拼音
Casting 类型转换 lèi xíng zhuǎn huàn
1.6

复合赋值运算符

大纲
Learning ObjectiveEssential Knowledge

1.6.A
Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.

  • 1.6.A.1 Compound assignment operators +=, -=, *=, /=, and %= can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right and then assigns the result to the variable on the left.
  • 1.6.A.2 The post-increment operator ++ and post-decrement operator -- are used to add 1 or subtract 1 from the stored value of a numeric variable. The new value is assigned to the variable.
    • Exclusion statement: The use of increment and decrement operators in prefix form (e.g., ++x) is outside the scope of the AP Computer Science A course and exam. The use of increment and decrement operators inside other expressions (e.g., arr[x++]) is outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

简写把一个运算与赋值结合:x += 5 意味着 x = x + 5;同样 -=*=/=%=自增(increment)和自减(decrement)运算符 x++x-- 加或减一。

1.7

应用程序接口(API)与库

大纲
Learning ObjectiveEssential Knowledge

1.7.A
Identify the attributes and behaviors of a class found in the libraries contained in an API.

  • 1.7.A.1 Libraries are collections of classes. An application programming interface (API) specification informs the programmer how to use those classes. Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API. A class defines a specific reference type. Classes in the APIs and libraries are grouped into packages. Existing classes and class libraries can be utilized to create objects.
  • 1.7.A.2 Attributes refer to the data related to the class and are stored in variables. Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.

来源:美国大学理事会 AP 课程与考试说明

一个 API(应用程序接口,Application Programming Interface)是你可以使用的类和方法的已发布列表。一个(library)是一个现成类的搜集(像 MathStringScanner)。你读 API 文档以学一个方法需要什么(它的参数)和返回什么,而不看它的内部代码——抽象(abstraction)的一个例子。

词汇表 训练
英文 中文 拼音
library
abstraction 抽象 chōu xiàng
Interface 应用程序接口 yìng yòng chéng xù jiē kǒu
1.8

用注释编写文档

大纲
Learning ObjectiveEssential Knowledge

1.8.A
Describe the functionality and use of code through comments.

  • 1.8.A.1 Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.
  • 1.8.A.2 A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
  • 1.8.A.3 A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.

来源:美国大学理事会 AP 课程与考试说明

注释(comments)被编译器忽略但向人类解释代码:// 用于单行、/* ... */ 用于一个块,而 /** ... */ 用于一个 Javadoc 注释,它记录一个方法的目的、参数和返回值。精确的前置条件(preconditions)和后置条件(postconditions)写在这里。

词汇表 训练
英文 中文 拼音
Comments 注释 zhù shì
1.9

方法签名

大纲
Learning ObjectiveEssential Knowledge

1.9.A
Identify the correct method to call based on documentation and method signatures.

  • 1.9.A.1 A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
  • 1.9.A.2 A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.

1.9.B
Describe how to call methods.

  • 1.9.B.1 A void method does not have a return value and is therefore not called as part of an expression.
  • 1.9.B.2 A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
  • 1.9.B.3 An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
  • 1.9.B.4 Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
  • 1.9.B.5 A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.

来源:美国大学理事会 AP 课程与考试说明

一个方法签名(method signature)是一个方法的名字加它的参数类型,例如 nextInt()substring(int, int)。要调用一个方法你必须提供在数量、类型和顺序上匹配参数的实参(arguments)。完整的方法头也陈述返回类型(return type)——方法返回的值的类型(若没有则是 void)——但返回类型不是签名的一部分,这就是为什么两个方法不能仅凭返回类型不同来区分。

词汇表 训练
英文 中文 拼音
method signature 方法签名 fāng fǎ qiān míng
arguments 实参 shí cān
1.10

调用类方法

大纲
Learning ObjectiveEssential Knowledge

1.10.A
Develop code to call class methods and determine the result of those calls.

  • 1.10.A.1 Class methods are associated with the class, not instances of the class. Class methods include the keyword static in the header before the method name.
  • 1.10.A.2 Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.

来源:美国大学理事会 AP 课程与考试说明

一个类(静态)方法(class (static) method)属于类本身,所以你在类名上调用它:ClassName.method(args)。不需要对象。

探索

Follow a class-method call on the stack

Calling a class method like Math.max pushes a new frame onto the call stack; when the method returns a value, its frame pops and control goes back to the caller. Step through to watch the stack grow and shrink.

词汇表 训练
英文 中文 拼音
class (static) method 类方法 lèi fāng fǎ
class lèi
1.11

Math 类

大纲
Learning ObjectiveEssential Knowledge

1.11.A
Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.

  • 1.11.A.1 The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
  • 1.11.A.2 The Math class contains only class methods. The following Math class methods—including what they do and when they are used—are part of the Java Quick Reference:
    • static int abs(int x) returns the absolute value of an int value.
    • static double abs(double x) returns the absolute value of a double value.
    • static double pow(double base, double exponent) returns the value of the first parameter raised to the power of the second parameter.
    • static double sqrt(double x) returns the nonnegative square root of a double value.
    • static double random() returns a double value greater than or equal to 0.0 and less than 1.0.
  • 1.11.A.3 The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range based on specified criteria. Each endpoint of the range can be inclusive, meaning the value is included, or exclusive, meaning the value is not included.

来源:美国大学理事会 AP 课程与考试说明

Math 类提供静态数学方法:Math.abs(x)Math.pow(base, exp)Math.sqrt(x),和 Math.random()($[0,1)$ 里的一个 double)。要得到一个从 0n-1 的随机整数:(int)(Math.random() * n)

1.12

对象:类的实例

大纲
Learning ObjectiveEssential Knowledge

1.12.A
Explain the relationship between a class and an object.

  • 1.12.A.1 An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
  • 1.12.A.2 A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass.
    • Exclusion statement: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam.
  • 1.12.A.3 All classes in Java are subclasses of the Object class.

1.12.B
Develop code to declare variables to store reference types.

  • 1.12.B.1 A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.

来源:美国大学理事会 AP 课程与考试说明

= 复制的是引用,不是对象

一个(class)是一个蓝图;一个对象(object)是从它构建的一个具体的实例(instance)。一个类把数据(字段)与行为(方法)捆绑——面向对象编程(object-oriented programming)的核心。StringScannerArrayList 都是你实例化的类。

类可以被组织成一个层级。一个父类(superclass)持有几个子类(subclasses)共享的属性和行为,这些子类 extend(扩展)它——一个继承关系(inheritance relationship)。Java 里每个类最终都是内置 Object 类的一个子类,这就是为什么每个对象已经有一个 toString 方法;写一个与父类方法有相同签名的子类方法就是方法重写(method overriding)。(设计你自己的继承超出本课程,但你要能识别这些词汇。)

一个类图:私有属性和公有方法
一个类图:私有属性和公有方法
一个类是一个蓝图;每个对象是从它构建的一个实例
一个类是一个蓝图;每个对象是从它构建的一个实例
词汇表 训练
英文 中文 拼音
object 对象 duì xiàng
instance 实例 shí lì
object-oriented programming 面向对象编程 miàn xiàng duì xiàng biān chéng
superclass 父类 fù lèi
subclasses 子类 zi lèi
inheritance relationship 继承关系 jì chéng guān xì
method overriding 方法重写 fāng fǎ zhòng xiě
reference 引用 yǐn yòng
1.13

对象的创建与存储(实例化)

大纲
Learning ObjectiveEssential Knowledge

1.13.A
Identify, using its signature, the correct constructor being called.

  • 1.13.A.1 A class contains constructors that are called to create objects. They have the same name as the class.
  • 1.13.A.2 A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
  • 1.13.A.3 Constructors are said to be overloaded when there are multiple constructors with different signatures.

1.13.B
Develop code to declare variables of the correct types to hold object references.

  • 1.13.B.1 A variable of a reference type holds an object reference or, if there is no object, null.

1.13.C
Develop code to create an object by calling a constructor.

  • 1.13.C.1 An object is typically created using the keyword new followed by a call to one of the class's constructors.
  • 1.13.C.2 Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
  • 1.13.C.3 A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
  • 1.13.C.4 A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.

来源:美国大学理事会 AP 课程与考试说明

实例化(instantiation)用 new 关键字创建一个对象,它调用一个构造函数(constructor):

Scanner in = new Scanner(System.in);
String s = new String("hi");   // or just "hi"

变量持有一个引用(reference)(对象的地址),不是对象本身。两个引用能指向同一个对象;用 == 比较它们比较地址,不是内容。

一个引用也能指向空:特殊值 null(空值)意味着“不附着于任何对象”。在一个 null 引用上调用一个方法会在运行时以一个 NullPointerException 崩溃。通过用 ==/!= 测试并检查 null 来防范,这样 && 在方法运行前短路:if (s != null && s.length() > 0)

一个基本变量直接持有它的值,一个引用持有指向对象的一个箭头
一个基本变量直接持有它的值,一个引用持有指向对象的一个箭头
词汇表 训练
英文 中文 拼音
Instantiation 实例化 shí lì huà
constructor 构造函数 gòu zào hán shù
null 空值 kōng zhí
1.14

调用实例方法

大纲
Learning ObjectiveEssential Knowledge

1.14.A
Develop code to call instance methods and determine the result of these calls.

  • 1.14.A.1 Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods.
  • 1.14.A.2 A method call on a null reference will result in a NullPointerException.

来源:美国大学理事会 AP 课程与考试说明

一个实例方法(instance method)作用于一个特定的对象,所以你在对象引用上调用它:object.method(args)。例:in.nextInt()word.length()

词汇表 训练
英文 中文 拼音
instance method 实例方法 shí lì fāng fǎ
1.15

字符串操作

大纲
Learning ObjectiveEssential Knowledge

1.15.A
Develop code to create string objects and determine the result of creating and combining strings.

  • 1.15.A.1 A String object represents a sequence of characters and can be created by using a string literal or by calling the String class constructor.
  • 1.15.A.2 The String class is part of the java.lang package. Classes in the java.lang package are available by default.
  • 1.15.A.3 A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
  • 1.15.A.4 Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object. A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
  • 1.15.A.5 A String object can be concatenated with any object, which implicitly calls the object's toString method (a behavior that is guaranteed to exist by the inheritance relationship every class has with the Object class). An object's toString method returns a string value representing the object. Subclasses of Object often override the toString method with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass.
    • Exclusion statement: Overriding the toString method of a class is outside the scope of the AP Computer Science A course and exam.

1.15.B
Develop code to call methods on string objects and determine the result of calling these methods.

  • 1.15.B.1 A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in a StringIndexOutOfBoundsException.
  • 1.15.B.2 The following String methods—including what they do and when they are used—are part of the Java Quick Reference:
    • int length() returns the number of characters in a String object.
    • String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1.
    • String substring(int from) returns substring(from, length()).
    • int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found.
    • boolean equals(Object other) returns true if this corresponds to the same sequence of characters as other; returns false otherwise.
    • int compareTo(String other) returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. Strings are ordered based upon the alphabet.
    • Exclusion statement: Using the equals method to compare one String object with an object of a type other than String is outside the scope of the AP Computer Science A course and exam.
  • 1.15.B.3 A string identical to the single element substring at position index can be created by calling substring(index, index + 1).

来源:美国大学理事会 AP 课程与考试说明

字符串不可变

String 对象是不可变(immutable)的——方法返回一个字符串而不是改变原来的。关键方法(所有索引从 0 开始):

s.length();            // number of characters
s.substring(2, 5);     // chars at index 2,3,4 (5 excluded)
s.indexOf("ab");       // first position, or -1
s.equals(other);       // content comparison (never use == for Strings)
s.compareTo(other);    // <0, 0, >0 by dictionary order

考试技能: substring(a, b) 包括索引 a排除 b,而字符串比较必须用 .equals,不是 == ——两个最被考查的字符串陷阱。

Worked example.String s = "COMPUTER";(索引 07)。那么 s.length()8;s.substring(0, 4)"COMP"(索引 0,1,2,3 ——索引 4 被排除);s.substring(4)"UTER"(从索引 4 到末尾);s.indexOf("PU")3;而 s.indexOf("X")-1(未找到)。数 substring 被排除的端点是单个最常见的失误。

请求一个在 0length()-1 之外的索引(一个坏的 substringcharAt 参数,例如这里的 s.substring(0, 20))会以一个 StringIndexOutOfBoundsException 崩溃——数组索引错误的字符串表亲。

字符串索引从 0 开始
字符串索引从 0 开始
探索

Explore string indices and slicing

Every character has an index, and the numbering starts at 0. Drag the start and end to see how substring(from, to) takes the characters from from up to — but not includingto.

词汇表 训练
英文 中文 拼音
immutable 不可变 bù kě biàn
1.15

考试技巧

  • 逐行手工跟踪代码,在一张表里追踪每个变量的值——考试奖励仔细的跟踪而不是猜测。
  • 知道 Java 的基本类型以及整数除法截断($7/2$ 给出 $3$);用一个转换或一个 double 做实数除法。
  • 区分编译时错误(语法、类型)和运行时错误——知道有名字的那些:ArithmeticException(int ÷ 0)、NullPointerException(在 null 引用上的方法)、StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException——和逻辑错误(错误的输出)。
  • 遵循运算符优先级并在你使用每个变量之前初始化它。
  • 在自由回答上,写完整的、可编译的 Java ——返回正确的类型并精确匹配方法头。

本主题的互动课程

逐步学习,并即时检测练习。

AP 计算机科学 A历年真题

AP 计算机科学 A的更多主题

登录或创建账号

IGCSE, A-Level & AP