技术文摘
十段超级实用的 Java 代码片段
2024-12-30 17:35:37 小编
十段超级实用的 Java 代码片段
在 Java 编程的世界里,掌握一些实用的代码片段可以大大提高开发效率。以下为您分享十段超级实用的 Java 代码片段。
- 字符串反转
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);
}
}
- 数组排序
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 + " ");
}
}
}
- 检查素数
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 + " 不是素数");
}
}
}
- 计算阶乘
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);
}
}
- 链表操作
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);
}
}
- 文件读取
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();
}
}
}
- 多线程示例
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();
}
}
- 异常处理
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);
}
}
- 集合操作
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);
}
}
}
- 日期时间处理
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 开发。
- VS2019 创建 Web 项目并发送至 IIS 及 IIS 与 ASP.NET 配置指南
- HTML 常用标签详尽整理
- CSS3 打造动态翻牌 仿百度贴吧 3D 单次翻牌动画特效
- ASP.NET Core WebSocket 集群的实现思路剖析
- WebStorm 配置 ESLint 实现一键格式化代码的详细方法
- ffmpeg 安装与音频转换指令运用
- Dart 中 8 个令人惊艳的用法深度解析
- ABAP OPEN SQL 注入漏洞的防御示例
- XSS 跨站脚本攻击的危害与防御策略解析
- 应对 App 与网站常见的几种攻击类型之方法
- 微信小程序服务器域名配置图文详解
- vscode 中 eslint 插件失效问题与解决办法
- ArcGIS Pro 中基于字段的融合与拆分操作步骤
- XPath 的定义、语法基础、示例运用与高级技法
- vscode eslint 插件报错:Invalid ecmaVersion 导致的解析错误