十段超级实用的 Java 代码片段

2024-12-30 17:35:37   小编

十段超级实用的 Java 代码片段

在 Java 编程的世界里,掌握一些实用的代码片段可以大大提高开发效率。以下为您分享十段超级实用的 Java 代码片段。

  1. 字符串反转
public class StringReversal {
    public static String reverseString(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }

    public static void main(String[] args) {
        String original = "Hello World";
        String reversed = reverseString(original);
        System.out.println(reversed);
    }
}
  1. 数组排序
import java.util.Arrays;

public class ArraySorting {
    public static void main(String[] args) {
        int[] numbers = {5, 1, 9, 3, 7};
        Arrays.sort(numbers);
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
  1. 检查素数
public class PrimeChecker {
    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int num = 7;
        if (isPrime(num)) {
            System.out.println(num + " 是素数");
        } else {
            System.out.println(num + " 不是素数");
        }
    }
}
  1. 计算阶乘
public class FactorialCalculator {
    public static long factorial(int num) {
        if (num == 0 || num == 1) {
            return 1;
        }
        return num * factorial(num - 1);
    }

    public static void main(String[] args) {
        int num = 5;
        long factorial = factorial(num);
        System.out.println(num + " 的阶乘为: " + factorial);
    }
}
  1. 链表操作
class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class LinkedListOperations {
    public static void printList(Node head) {
        Node curr = head;
        while (curr!= null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);

        head.next = second;
        second.next = third;

        printList(head);
    }
}
  1. 文件读取
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReading {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("your_file.txt"))) {
            String line;
            while ((line = reader.readLine())!= null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 多线程示例
public class MultiThreadingExample extends Thread {
    @Override
    public void run() {
        System.out.println("Hello from thread: " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MultiThreadingExample thread1 = new MultiThreadingExample();
        MultiThreadingExample thread2 = new MultiThreadingExample();

        thread1.start();
        thread2.start();
    }
}
  1. 异常处理
public class ExceptionHandling {
    public static int divide(int num1, int num2) {
        try {
            return num1 / num2;
        } catch (ArithmeticException e) {
            System.out.println("除数不能为 0");
            return 0;
        }
    }

    public static void main(String[] args) {
        int result = divide(5, 0);
        System.out.println("结果: " + result);
    }
}
  1. 集合操作
import java.util.HashSet;
import java.util.Set;

public class CollectionOperations {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple");

        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}
  1. 日期时间处理
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeHandling {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = format.format(date);
        System.out.println(formattedDate);
    }
}

这些 Java 代码片段涵盖了多个常见的编程场景,熟练掌握它们将有助于您更高效地进行 Java 开发。

TAGS: Java 代码片段 Java 实用技巧 超级 Java 代码 Java 编程精华

欢迎使用万千站长工具!

Welcome to www.zzTool.com