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

常用Java函数的示例及实现方法

发布时间:2023-07-01 11:31:12

Java是一种面向对象的编程语言,它提供了许多常用的函数和方法,可以帮助开发人员实现各种功能。下面是一些常用的Java函数的示例及实现方法:

1. 数学函数:

- Math.sqrt(double a):返回参数的平方根。

- Math.pow(double a, double b):返回a的b次幂。

- Math.random():返回一个0到1之间的随机数。

- Math.abs(int a):返回参数的绝对值。

示例代码:

   double result = Math.sqrt(16);
   System.out.println("平方根:" + result);

   double result2 = Math.pow(2, 3);
   System.out.println("2的3次方:" + result2);

   int randomNum = (int) (Math.random() * 10);
   System.out.println("随机数:" + randomNum);

   int absNum = Math.abs(-10);
   System.out.println("绝对值:" + absNum);
   

2. 字符串函数:

- String.length():返回字符串的长度。

- String.charAt(int index):返回指定索引位置的字符。

- String.substring(int beginIndex, int endIndex):返回子字符串。

- String.indexOf(String str):返回字符串中 次出现的指定子字符串的索引。

示例代码:

   String str = "Hello World";
   int length = str.length();
   System.out.println("字符串长度:" + length);

   char ch = str.charAt(0);
   System.out.println("      个字符:" + ch);

   String substring = str.substring(6, 11);
   System.out.println("子字符串:" + substring);

   int index = str.indexOf("World");
   System.out.println("子字符串索引:" + index);
   

3. 数组函数:

- Arrays.sort(int[] a):对数组进行升序排序。

- Arrays.toString(int[] a):将数组转换为字符串。

- Arrays.fill(int[] a, int val):将数组的所有元素都设置为指定的值。

- Arrays.copyOf(int[] original, int newLength):将数组复制到一个新的数组中。

示例代码:

   int[] arr = {5, 2, 8, 3, 1};
   Arrays.sort(arr);
   System.out.println("排序后的数组:" + Arrays.toString(arr));

   int[] newArr = Arrays.copyOf(arr, 10);
   System.out.println("复制后的数组:" + Arrays.toString(newArr));

   Arrays.fill(arr, 0);
   System.out.println("填充后的数组:" + Arrays.toString(arr));
   

4. 时间日期函数:

- LocalDateTime.now():获取当前日期和时间。

- LocalDate.of(int year, int month, int dayOfMonth):创建指定日期的LocalDate对象。

- LocalDate.plusDays(long daysToAdd):将天数添加到日期。

示例代码:

   LocalDateTime now = LocalDateTime.now();
   System.out.println("当前日期和时间:" + now);

   LocalDate date = LocalDate.of(2022, 1, 1);
   System.out.println("指定日期:" + date);

   LocalDate newDate = date.plusDays(7);
   System.out.println("添加7天后的日期:" + newDate);
   

5. 文件操作函数:

- File.exists():判断文件是否存在。

- File.isDirectory():判断是否是文件夹。

- File.isFile():判断是否是文件。

- File.delete():删除文件。

示例代码:

   File file = new File("example.txt");
   boolean exists = file.exists();
   System.out.println("文件是否存在:" + exists);

   boolean isDirectory = file.isDirectory();
   System.out.println("是否是文件夹:" + isDirectory);

   boolean isFile = file.isFile();
   System.out.println("是否是文件:" + isFile);

   boolean deleted = file.delete();
   System.out.println("文件是否被删除:" + deleted);
   

这些是Java中一些常用的函数的示例及实现方法。通过使用这些函数,可以实现各种不同的功能,简化开发过程并提高效率。