Arrays类和Math类

Arrays类

概述

 java.util.Arrays此类主要是用来操作数组,里面提供了许多的操作方法,如【排序】和【搜索】功能。其所有方法均为静态方法,调用起来十分简单。

操作数组的方法

  • public static String toString(int[] a): 返回指定数组内容的字符串表示形式。
public static void main(String[] args){
	int[] arr={1,2,4,7,5};
	//把数组内容转换成字符串
	String str=Arrays.toString(arr);
	System.out.println(str);//[1,2,4,7,5]
}
  • public static void sort(int[] arr): 对指定的int数组进行升序排序
public static void main(String[] args){
	int[] arr={1,2,4,7,5};
	//输出排序前
	System.out.println(Arrays.toString(arr));//[1,2,4,7,5]
	//升序排序
	Arrays.sort(arr);
	System.out.println(Arrays.toString(arr));//[1,2,4,5,7]
}
  • public static int binarySearch(int[] a, int key)

  使用二分搜索法来搜索指定的 int 型数组,以获得指定的值。key指的是要搜索的值,返回值int指的是搜索值对应的索引值。

  注意:使用 binarySearch()方法,数组必须是有序(升序)的。

public static void main(String[] args){
	int[] arr={10,30,20,5,60};
	//升序
	Arrays.sort(arr);
	//搜索5在arr中的索引值
	int index=Arrays.binarySearch(arr,5);
	System.out.println(index);
}
  • public static void fill(int[] arr,int val) :将指定的int值分配给指定的int 数组的每个元素
public static void main(String[] args) {
    // 定义一个int数组
    int[] arr = {10,20,5,30,40,15,18};
    
    // 想要把100元素值分配给arr数组
    Arrays.fill(arr,100);
    
    // 打印输出
    System.out.println(Arrays.toString(arr));//[100, 100, 100, 100, 100, 100, 100]
}

Math类

概述
 java.util.Math包含了用于执行基本数学运算的方法。里面的方法均是静态方法。

基本运算方法

  • public static double abs(double a) :返回double值的绝对值
double d1 = Math.abs(-5.3);// d1的值为5.3
double d2 = Math.abs(5.3);//  d2的值为5.3
double d3 = Math.abs(0.0);//  d3的值为0.0  
  • public static double ceil(double a) :返回大于等于参数的最小整数,往上取整。
double d1 = Math.ceil(5.3);// d1的值为6.0
double d2 = Math.ceil(5.9);// d2的值为6.0
double d3 = Math.ceil(-5.9);// d3的值为-5.0
  • public static double floor(double a) :返回小于等于参数的最小整数,往下取整。
double d1 = Math.floor(5.9);// d1的值为5.0
double d2 = Math.floor(5.1);// d2的值为5.0
double d3 = Math.floor(-5.9);// d3的值为-6.0
  • public static long round(double a) : 返回最接近参数的long类型值。(相当于四舍五入运算)。
long d1 = Math.round(5.5);// d1的值为6
long d2 = Math.round(5.4);// d2的值为5
long d3 = Math.round(-5.5);// d3的值为-5
long d4 = Math.round(-5.6);// d4的值为-6

练习:使用Math类相关的api方法,计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个,分别是哪些数字?

public static void main(String[] args) {
    double max = 5.9;
    double min = -10.8;
    int count = 0;// 统计个数
    // 遍历循环 获取整数
    for (double i = Math.ceil(min) ; i <= Math.floor(max); i++) {
        // 判断条件
        if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
            System.out.print(i + " ");
            count++;
        } 
    }
    System.out.println();
    // 打印输出个数
    System.out.println("满足条件整数个数为:" + count + "个");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值