Java 语法

Java 语法过关。

看注释理解,有其他语言基础还是容易上手的。
( Java 手敲起来看着很长,但是用上 IDEA 就会有种被读心的感觉)

基本框架

dfs 求全排列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 导入包
import java.io.*;
import java.util.Scanner;

public class Main {

// 定义全局变量
private static int[] res;
private static boolean vis[];
private static int n;
private final static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

// 主函数
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
res = new int[n];
vis = new boolean[n];
dfs(0);
bw.flush();
}

// 自定义函数
private static void dfs(int u) throws Exception {
if (u == n) {
for(int i = 0; i < n; i++){
bw.write(res[i] + " ");
}
bw.write("\n");
return;
}

for(int i = 0; i < n; i++) {
if(vis[i]) continue;

res[u] = i + 1;
vis[i] = true;
dfs(u + 1);
vis[i] = false;
}

}
}

类的使用

三元组的排序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Arrays;
import java.util.Scanner;

class tuple implements Comparable<tuple> {
// 定义成员变量
int x;
double y;
String z;

// 构造函数
public tuple(int x, double y, String z) {
this.x = x;
this.y = y;
this.z = z;
}

// 实现接口 Comparable<tuple>
public int compareTo(tuple o) {
return x - o.x;
}

// 成员函数
public void output() {
System.out.printf("%d %.2f %s\n", x, y, z);
}

}

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
tuple[] a = new tuple[n];
for (int i = 0; i < n; i++) {
a[i] = new tuple(sc.nextInt(), sc.nextDouble(), sc.next());
}
Arrays.sort(a);
for (int i = 0; i < n; i++) {
a[i].output();
}
}
}

继承、多态与接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.Scanner;

// 定义接口
interface Role {
public void greet();
public void move();
public int getSpeed();
}

// 继承接口
interface Hero extends Role {
public void attack();
}

// 多个类实现接口
class Athena implements Hero {
private final String name = "Athena";
public void attack() {
System.out.println(name + ": Attack!");
}

public void greet() {
System.out.println(name + ": Hi!");
}

public void move() {
System.out.println(name + ": Move!");
}

public int getSpeed() {
return 10;
}
}

class Zeus implements Hero {
private final String name = "Zeus";
public void attack() {
System.out.println(name + ": Attack!");
}

public void greet() {
System.out.println(name + ": Hi!");
}

public void move() {
System.out.println(name + ": Move!");
}

public int getSpeed() {
return 10;
}
}

public class Main {
public static void main(String[] args) {
Hero[] heros = {new Zeus(), new Athena()};
for (Hero hero: heros) {
// 多态 共用hero接口
hero.greet();
}
}
}