Arrays类和Math类
1. Arrays类
此类包含用来操作数组(比如排序和搜索)的各种方法。此类还包含一个允许将数组作为列表来查看的静态工厂。
- public static string toString(数组):将参数数组变成字符串(按照默认格式: [元素1, 元素2,元素3…]) .
- public static void sort(数组):按照默认升序(从小到大)对数组的元素进行排序。
- 备注:
①如果是数值,sort默认按照升序从小到大。
②如果是字符串,sort默认按照字母升序。
③如果是自定义的类型,那么这个自定义的类需要有Comparable或者Comparator 接口的支持。
import java.util.Arrays;
/**
* Arrays类的相关操作
* @author 86178
*/
public class TestArrays{
public static void main(String[] args) {
int[] inArrays = {10,20,30};
//将int数组转换为默认格式的字符串
String str = Arrays.toString(inArrays);
System.out.println(str);
//将数组进行默认排序
int[] arrays = {3,5,2,20,22,11,25};
//返回的是空类型
Arrays.sort(arrays);
System.out.println(Arrays.toString(arrays));
//将字母进行排序
String[] str1 = {"aaa","bbb","ccc"};
Arrays.sort(str1);
System.out.println(Arrays.toString(str1));
}
}
练习:字符串倒序输出
import java.util.Arrays;
/**
* Arrays类字符串数组倒序
* @author 86178
*/
public class TestString {
public static void main(String[] args) {
String str = "hjascv/ljQGF121EG7`UID功夫";
//将字符串转换为字符数组
char[] strings = str.toCharArray();
//进行升序
Arrays.sort(strings);
//倒序输出
for (int i = strings.length - 1; i >= 0; i--) {
System.out.print(strings[i]);
}
}
}
2. Math类
Math
类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
- public static double abs(double num)获取绝对值。
- public static double ceil(double num); 向上取整。
- public static double floor(double num)1 向下取整。
- public static long round(double num); 四舍五入。
//返回最大值
System.out.println(Math.max(12,23));
//返回两数平方和
System.out.println(Math.hypot(2.11,3.21));
//返回绝对值
System.out.println(Math.abs(-111));
//向上下取整
System.out.println(Math.ceil(12.11));
System.out.println(Math.floor(12.11));
//四舍五入
System.out.println(Math.round(12.11));
//随机数 大于等于 0.0 且小于 1.0 的伪随机 double 值。
System.out.println(Math.random());
数学题:
计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数的个数
思路:
-
首先确定了范围,用for循环
-
起点-10.8应该转换为-10,有两种方法:
①Math.ceil向上取整
②强转为int类型,自动舍弃小数位
-
每一个数字都是整数,所以表达式应该是num++,这样每次都是加一的
-
拿到绝对值Math.abs()
-
一旦发现这个数字,需要让计数器进行统计
/**
* 小学数学题
* @author 86178
*/
public class TestMath {
public static void main(String[] args) {
//计数器
int count = 0;
double min = -10.8;
double max = 2.1;
for (int i = (int)Math.ceil(min); i < max ; i++) {
int abs = Math.abs(i);
if (abs > 6 || abs < 2.1){
System.out.println(i);
count++;
}
}
System.out.println("总数是:" + count);
}
}