常用API学习04(Java)
发布人:shili8
发布时间:2025-01-10 02:16
阅读次数:0
**常用API学习04(Java)**
在前面的几篇文章中,我们已经学习了 Java 中一些常用的 API,包括 `String`、`Arrays` 和 `Collections` 等。今天我们将继续学习另外几个重要的 API:`Math`、`Random` 和 `Date`。
###1. Math API`Math` API 提供了一系列用于数学运算的方法,例如平方根、对数、余弦等。这些方法都静态方法,因此可以直接通过类名调用。
#### 示例代码:
javaimport java.lang.Math;
public class MathExample {
public static void main(String[] args) {
// 平方根 double sqrt = Math.sqrt(9);
System.out.println("平方根:" + sqrt);
// 对数 double log = Math.log(10);
System.out.println("对数:" + log);
//余弦 double cos = Math.cos(Math.PI /2);
System.out.println("余弦:" + cos);
// 最大值和最小值 int[] arr = {1,3,5,7};
int max = Math.max(arr[0], arr[1]);
int min = Math.min(arr[0], arr[1]);
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
// absolute double abs = Math.abs(-5.6);
System.out.println("绝对值:" + abs);
}
}
###2. Random API`Random` API 提供了一系列用于生成随机数的方法。这些方法都静态方法,因此可以直接通过类名调用。
#### 示例代码:
javaimport java.util.Random;
public class RandomExample {
public static void main(String[] args) {
// nextInt int random = new Random().nextInt(10);
System.out.println("随机数:" + random);
// nextDouble double randomDouble = new Random().nextDouble();
System.out.println("随机双精度浮点数:" + randomDouble);
// nextBoolean boolean randomBoolean = new Random().nextBoolean();
System.out.println("随机布尔值:" + randomBoolean);
}
}
###3. Date API`Date` API 提供了一系列用于处理日期和时间的方法。这些方法都静态方法,因此可以直接通过类名调用。
#### 示例代码:
javaimport java.util.Date;
public class DateExample {
public static void main(String[] args) {
// getCurrentTime long currentTime = System.currentTimeMillis();
System.out.println("当前时间(毫秒):" + currentTime);
// getCurrentDate Date currentDate = new Date();
System.out.println("当前日期:" + currentDate);
// parse String dateStr = "2022-01-0112:00:00";
Date parsedDate = Date.parse(dateStr);
System.out.println("解析的日期:" + parsedDate);
// format String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println("格式化的日期:" + formattedDate);
}
}
### 总结在本篇文章中,我们学习了 Java 中 `Math`、`Random` 和 `Date` API 的使用方法。这些 API 提供了一系列用于数学运算、生成随机数和处理日期和时间的方法。通过掌握这些 API,开发者可以更好地解决实际问题。
### 最后如果你有任何疑问或需要进一步学习,请在评论区留言。

