数组工具类Arrays
java.util.Arrays是一个与数组相关的工具类,里面提供了大量静态方法,用来实现数组常见的操作
public static String toString(数组):将参数数组变成字符串(按照默认格式:[元素1,元素2,元素3…])
public static void sort(数组):按照默认升序(从小到大)对数组的元素进行排序
备注:
- 如果是数值,sort默认按照升序从小到大
- 如果是字符串,sort默认按照字母升序
- 如果是自定义的类型,那么这个自定义的类需要Comparable或者Comparator接口的支持
package Practice;
import java.util.Arrays;
public class Practice6 {
public static void main(String[] args) {
int[] array1={1,4,5,3,37,6,49};
String str=Arrays.toString(array1);
System.out.println(str);
int[] array2={2,3,5,4,7,1,6};
Arrays.sort(array2);
System.out.println(Arrays.toString(array2));
String[] array3={"aaa","ccc","bbb"};
Arrays.sort(array3);
System.out.println(Arrays.toString(array3));
}
}
Arrays练习:字符串倒序排列
题目:将一个随机字符串中的所有字符升序排列,并倒序打印
package Practice;
import java.util.Arrays;
public class Practice6 {
public static void main(String[] args) {
String str="ajfhsnfrnewogi";
//如何进行升序排列 sort
// 必须是数组才能用Arrays.sort方法
//String-->数组,用toCharArray
***char[] chars=str.toCharArray();***
Arrays.sort(chars);//升序排列
//倒序遍历
for (int i = chars.length - 1; i >= 0; i--) {
System.out.println(chars[i]);
}
}
}
注意:倒序遍历快捷键 对象名.forr+enter
Math
java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作
public static double abs (double num):获取绝对值
public static double ceil(double num):向上取整
public static double floor (double num):向下取整
public static long round(double num):四舍五入
Math.PI代表近似的圆周率常量
package Practice;
import java.util.Arrays;
public class Practice6 {
public static void main(String[] args) {
//取绝对值
System.out.println(Math.abs(3.14));
System.out.println(Math.abs(-2.5));
System.out.println(Math.abs(0));
//向上取整
System.out.println(Math.ceil(3.9));
System.out.println(Math.ceil(2.1));
//向下取整
System.out.println(Math.floor(5.9));
//四舍五入
System.out.println(Math.round(4.6));
}
}
Math练习题
题目:计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
分析:
- 既然已经确定了范围,for循环
- 起点位置-10.8应该转换成-10,两种办法:2.1可以使用Math.ceil方法,向上取整 2.2强转成为int,自动舍弃所有小数位
- 每一个数字都是整数,所以步进表达式应该是num++
- 如何拿到绝对值:Math.abs方法
- 一旦发现一个数字,需要让计数器++进行统计
package Practice;
import java.util.Arrays;
public class Practice6 {
public static void main(String[] args) {
double min=-10.8;
double max=5.9;
int count=0;
for(int i=(int)min;i<max;i++){
int abs=Math.abs(i);
if(abs>6||abs<2.1){
System.out.println(i);
count++;
}
}
System.out.println("总共有:"+count+"个");
}
}