目录
0.常用方法 String、Integer、List、Queue、Stack、HashMap
2. 输出 print
import java.util.*; Scanner sc = new Scanner(System.in).useDelimiter("\\D")设置忽略的分隔符
连续数字,空格分隔直接读:
- // 读入一行n,第二行存入数组(法一)
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int[] arr = new int[n];
- for (int i = 0; i < n; i++) {
- arr[i] = sc.nextInt();
- }
读入以空格/逗号分隔的数组:
- // 读入首行 n 和 k (法二)
- Scanner sc = new Scanner(System.in);
- String[] line1 = sc.nextLine().split(" ");
- int n = Integer.parseInt(line1[0]);
- int k = Integer.parseInt(line1[1]);
-
- // 存入数组(以空格或逗号分隔的数据)
- String[] line2 = sc.nextLine().split(" ");
- int[] arr = new int[n];
- for (int i = 0; i < line2.length; i++) {
- arr[i] = Integer.parseInt(line2[i]);
- }
读入带框数组/链表:
- Scanner sc = new Scanner(System.in);
- String strs = sc.nextLine();
- // 处理字符串
- // 输入格式不标准直接return
- if (strs == null || strs.charAt(0) != '[' || strs.charAt(strs.length()-1) != ']') return;
- String[] str = strs.substring(1,strs.length()-1).split(",");
- //长度唯一的特殊情况直接return
- if (str.length == 1) System.out.println(strs);return;
- long[] nums = new long[str.length];
- for (int i = 0; i < str.length; i++) {
- nums[i] = Long.parseLong(str[i]);
- }
import java.io.*; BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- public static void main(String[] args) throws IOException {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//创建实例
- String str = br.readLine(); //读取一行字符串
- String[] temp=br.readLine().split(" "); //读取一行字符串,按空格分隔为字符串数组
- }
按空格分隔输出数组:
- // 输出数组,以空格分隔
- public static void printarr(int[] arr) {
- for (int i = 0; i < arr.length; i++) {
- if (i != arr.length-1) {
- System.out.print(arr[i] + " ");
- } else {
- System.out.print(arr[i]);
- }
- }
- }
按照带框格式输出链表:
- // 按格式输出链表
- public static void PrintList(ListNode head) {
- if (head == null) return;
- ListNode cur = head.next;
- System.out.print("{" + head.val);
- while (cur != null) {
- System.out.print("," + cur.val);
- cur = cur.next;
- }
- System.out.print("}");
- }