Java basics: classes, main, and output · Java 基础:类、main 和输出
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
AP Computer Science A uses Java
- The AP CSA exam is written in Java.
- Java is strict: every program lives inside a class, and starts from a method called main.
- You already think like a programmer — here we learn Java's rules.
中文
AP 计算机科学 A 使用 Java
- AP CSA 考试用 Java 语言。
- Java 很严格:每个程序都写在一个类(class)里面,并从一个叫 main 的方法开始运行。
- 你已经具备程序员的思维 —— 这里我们学习 Java 的规则。
English
The Java skeleton
- A tiny Java program looks like the example below. Your code goes inside main.
System.out.println(...)prints one line of text (like Python'sprint).- Every statement ends with a semicolon
;.
中文
Java 的基本骨架
- 一个最小的 Java 程序就像下面的例子。你的代码写在 main 里面。
System.out.println(...)打印一行文字(就像 Python 的print)。- 每一条语句都以分号
;结尾。
public class Main {
public static void main(String[] args) {
System.out.println("Java runs from inside main.");
int year = 12;
System.out.println("Grade " + year);
}
}
English
Types
- Java needs a type for every variable:
int(whole number),double(decimal),boolean(true/false),String(text). - You write the type first:
int score = 10;. - Join text and values with
+:"Grade " + yearmakesGrade 12.
中文
类型
- Java 要求每个变量都有一个类型(type):
int(整数)、double(小数)、boolean(真/假)、String(文本)。 - 类型写在前面:
int score = 10;。 - 用
+把文字和数值拼接起来:"Grade " + year得到Grade 12。
English
Common mistakes
- Every statement ends with
;. mainmust be exactlypublic static void main(String[] args).
中文
常见错误
- 每条语句以
;结尾。 main必须正好是public static void main(String[] args)。
English
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 里面,或者补全给出的方法。
- 按运行来编译并运行,然后按检查答案。
- 你的代码在服务器上编译并运行,所以第一次运行也很快。
Inside · 内部 main, use System.out.println(...) to print exactly Hello, AP CSA! · 在 main 里面,用 System.out.println(...) 精确地打印 **Hello, AP CSA!**
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete the method square(int n) so it returns n * n. The checker calls it with several values. · 完成方法 square(int n),让它返回 n * n。检查器会用多个数值来调用它。
Click Run to see the output here. · 点击“运行”查看此处输出。