一、固定代码结构
Java 没有裸写 main 的说法,必须套类,且类名必须是英文大写开头(Eclipse 要求),直接写一个公共类即可,所有逻辑都在 main 方法里,和 C++ 的 main 逻辑完全一致:
// 类名必须和文件名一致,比如文件叫Main.java,类名就必须是Main(蓝桥杯统一用Main就行) public class Main { // 全局变量(比如数组、常量)必须加static,否则main里不能直接用 public static final int N = 100010; public static int[] arr = new int[N]; // 主方法固定格式,背下来! public static void main(String[] args) { // 你的解题逻辑(和C++的main里完全一样,只是语法换Java) // 比如暴力枚举、递推、BFS/DFS等 } // 自定义函数(比如DFS、素数判断)也必须加static,否则main里不能直接调用 public static boolean isPrime(int x) { if (x < 2) return false; for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) return false; } return true; } }二、输入输出
对于大数据输入题(比如 1e5 行数据),用Scanner会直接超时,这是 Java 组的高频坑,你需要掌握两种输入方式(小数据用 Scanner,大数据用 BufferedReader),输出用System.out即可。
- 小数据 Scanner(简单,适合暴力 / 递推题):
import java.util.Scanner; // 必须导包,和C++的#include一样 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); // 读整数,对应C++的scanf("%d", &a) long b = sc.nextLong(); // 读长整数,对应C++的long long String s = sc.next(); // 读字符串(无空格) sc.close(); // 可选,省赛不用关也没事 } }
- 大数据 BufferedReader:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { // 必须抛IOException,否则编译报错 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(br.readLine()); // 读一行转整数 long b = Long.parseLong(br.readLine()); // 读一行转长整数 String s = br.readLine(); // 读一行字符串 // 读多个数:先读行,再分割 String[] parts = br.readLine().split(" "); int c = Integer.parseInt(parts[0]); int d = Integer.parseInt(parts[1]); } }
三、Java 基础数据类型 + 大数类
遇到高精度加减乘除、大素数判断、大阶乘等题,直接调 API 就行,不用写任何逻辑,这是 Java 组比 C++ 组轻松的点。
- 基础类型:记住Java 没有 long long,8 字节整数用
long(声明时加 L,比如10000000000L),避免int溢出(C++ 里的 int 溢出坑 Java 也有,只是类型名不同)。- 大数类 BigInteger(省赛核心,只需掌握加减乘除、取模):
import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); BigInteger a = sc.nextBigInteger(); BigInteger b = sc.nextBigInteger(); BigInteger add = a.add(b); // 加,不能用+ BigInteger sub = a.subtract(b); // 减,不能用- BigInteger mul = a.multiply(b); // 乘,不能用* BigInteger div = a.divide(b); // 除,不能用/ BigInteger mod = a.mod(b); // 取模 System.out.println(add); } }
四、集合框架
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); // 对应vector的push_back list.add(2); int x = list.get(0); // 对应vector的[0] int len = list.size(); // 对应vector的size() for (int i = 0; i < len; i++) { // 遍历,和C++一样 System.out.println(list.get(i)); } } }