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; }
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.greet(); } } }
|