欢迎访问宙启技术站
智能推送

Java函数库及常用函数示例

发布时间:2023-06-01 06:15:20

Java是一种流行的编程语言,有很多不同的函数库和函数可供使用。这篇文章将介绍一些常见的Java函数库和函数。

1. java.lang.Math

java.lang.Math库包含了一些基本的数学函数,如sin,cos,tan等三角函数,以及sqrt,abs,ceil等函数。

例如,下面的代码使用Math.sin函数计算角度为30度的正弦值:

double degrees = 30.0;
double radians = Math.toRadians(degrees);
double sinValue = Math.sin(radians);
System.out.println("sinValue is " + sinValue);

输出:sinValue is 0.5

2. java.util.Arrays

java.util.Arrays库包含了一些常见的数组操作函数,如排序,复制,搜索等。

例如,下面的代码使用Arrays.sort函数对一个整数数组进行排序:

int[] numbers = {3, 1, 4, 1, 5, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));

输出:[1, 1, 3, 4, 5, 9]

3. java.util.Collections

java.util.Collections库包含了一些常见的集合操作函数,如排序,查找,反转等。

例如,下面的代码使用Collections.sort函数对一个字符串列表进行排序:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Collections.sort(names);
System.out.println(names);

输出:[Alice, Bob, Charlie]

4. java.time.LocalDateTime

java.time.LocalDateTime库包含了一些常见的日期时间操作函数,如比较,格式化,解析等。

例如,下面的代码使用LocalDateTime.now函数获取当前日期时间并格式化输出:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String formattedDateTime = now.format(formatter);
System.out.println("Current date and time is " + formattedDateTime);

输出:Current date and time is 2021-07-01 11:30:00

5. java.lang.String

java.lang.String库包含了一些常见的字符串操作函数,如连接,查找,替换等。

例如,下面的代码使用String.split函数将一个逗号分隔的字符串拆分成一个字符串数组:

String csv = "1,2,3,4,5";
String[] values = csv.split(",");
System.out.println(Arrays.toString(values));

输出:[1, 2, 3, 4, 5]

6. java.util.Scanner

java.util.Scanner库提供了一个用于从标准输入流读取基本类型和字符串的简单方法。

例如,下面的代码使用Scanner.nextInt函数从控制台读取一个整数并输出:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int value = scanner.nextInt();
System.out.println("You entered " + value);

输出:Enter an integer: 42

You entered 42

7. java.io.File

java.io.File库提供了一些常见的文件和目录操作函数,如创建,删除,重命名等。

例如,下面的代码使用File类创建一个新的文件并输出它的路径:

File file = new File("example.txt");
if (file.createNewFile()) {
    System.out.println("File created: " + file.getAbsolutePath());
} else {
    System.out.println("File already exists.");
}

输出:File created: C:\Users\user\example.txt

总结

以上是Java常见的函数库和函数,这些函数在开发Java应用程序时非常有用。读者可以根据自己的需要查找更多的函数和库来提高开发效率和代码质量。