第4章 常用类
4.1 Math类
Math类是用于数学计算的一个工具类
对于工具类而言,里面的大部分成员都是静态的static
自带常量
- static double E:自然对数
- static double PI:圆周率
- static double ceil(double a):向上取整
- static double floor(double a):向下取整
- static long round(double a):四舍五入
Math.ceil(2.1) 返回3.0
Math•ceil^2 •0) 返回 2 •0
Math.ceilf-2.0)返回 -2.0
Math.ceil(-2.1) 返回 -2.0
Math.floor(2.1) 返回2 - 0
Math.floor(2.0) 返回 2.0
Math.floor(-2.0) 返回-2.0
Math.floor(-2.1)返回-3.0
Math.rint(2.1)返回 2.0
Math.rint(-2.0)返回 -2.0
Math.rint(-2.1) 返回-2.0
Math.rint(2.S) 返回2.0
Math.rint(4.5) 返回4.0
Math.rint(-2.5)返回 -2.0
Math,round(2.6f) 返回3 // Returns int
Math.round(2.0) 返回2 // Returns long
Math.round(-2.0f) 返回-2 // Returns int
Math.round(-2.6) 返回-3 // Returns long
Math.round(-2.4) 返回-2 // Returns long
- static double sin(double a):正弦函数 参数是弧度值
- static double cos(double a):余弦函数
- static double tan(double a):正切函数
- static double toDegrees(double a):将弧度转角度
- static double toRadians(double angles):将角度转弧度
- static double asin(double a):反正弦函数
- static double acos(double a):反余弦函数
- static double atan(double a):反正切函数
- static double pow(double a, double b):求a的b次幂
- static double sqrt(double a):求a的平方根
- static double cbrt(double a):求a的立方根
exp(x) | 返回 e 的 x 次方 |
log(x) | 返回 x 的自然底数 |
log10(x) | 回 x 的以 10 为底的对数 |
pow(a, b) | 返回 a 的 b 次方 |
sqrt(x) | 对于 x >=0 的数字,返回 x 的平方根 |
Math.exp(l) 返回 2.71828
Math,log(Math.E) 返回 1.0
Math.loglO(lO) 返回 1.0
Math.pow(2, 3) 返回 8.0
Math.pow(3, 2) 返回 9.0
Math.pow(4.5, 2.5) 返回 22.9176S
Math.sqrt(4) 返回 2.0
Math.sqrt(lO.S) 返回 4.24
其他方法
- static double abs(double a):求a的绝对值
- static double hypot(double deltX, double deltY):返回两点间距离
- static double max(a,b):返回a和b之间的最大值
- static double min(a,b):返回a和b之间的最小值
- static double random():返回[0,1)之间的随机小数
public class Sample {
public static void main(String[] args) {
System.out.println(Math.E);
System.out.println(Math.PI);
System.out.println(Math.ceil(3.1));
System.out.println(Math.ceil(3.9));
System.out.println(Math.ceil(-3.1));
System.out.println(Math.ceil(-3.9));
System.out.println(Math.floor(3.1));
System.out.println(Math.floor(3.9));
System.out.println(Math.floor(-3.1));
System.out.println(Math.floor(-3.9));
System.out.println(Math.round(3.1));
System.out.println(Math.round(3.9));
System.out.println(Math.round(-3.1));
System.out.println(Math.round(-3.9));
System.out.println(Math.sin(Math.PI/6));
System.out.println(Math.cos(Math.PI/3));
System.out.println(Math.tan(Math.PI/4));
System.out.println(Math.toDegrees(Math.PI/2));
System.out.println(Math.toRadians(90));
System.out.println(Math.cbrt(8));
System.out.println(Math.hypot(0 - 1, 0 - 1));
}
}
Math.max (2, 3) 返回 3
Math.max (2. Sf 3) 返回 3.0
Math.min (2.5, 4.6) 返回 2.S
Math.abs(-2) 返回 2
Math.abs(-2.1) 返回 2.1
4.2 Scanner类
主要用于负责数据输入的类,底层是和IO流相关。
- String next():获取直到遇到空格为止的一个字符串
- String nextLine():获取直到遇到回车为止的一个字符串
- int nextInt():获取下一个整数 byte short long
- double nextDouble()
- boolean nextBoolean()
- float nextFloat()
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入一句话:");
String line = input.nextLine();
System.out.println(line);
System.out.print("输入三个单词:");
String word1 = input.next();
String word2 = input.next();
String word3 = input.next();
System.out.println(word1);
System.out.println(word2);
System.out.println(word3);
}
}
4.3 Random类
主要用于产生随机数
- boolean nextBoolean():随机产生布尔类型值
- double nextDouble():随机生成0.0~1.0之间的小数
- double nextInt():随机生成一个整数0~2^32的整数
- double nextInt(n):随机生成一个整数[0,n)的整数
import java.util.Random;
public class Sample {
public static void main(String[] args) {
Random random = new Random();
for (int i = 1; i <= 10; i++) {
System.out.print(random.nextBoolean() + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++) {
System.out.print(random.nextInt(2) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++) {
System.out.print(random.nextInt() + " ");
}
System.out.println();
}
}
字符型数据与数值型数据之间的转换
为了强制陚值,就必须使用显式转换方式:
如下所示: byte b = (byte) •\uFFF4';
0 ~ FFFF 的任何一个十六进制正整数都可以隐式地转换成字符型数据。而不在此范围 内的任何其他数值都必须显式地转换为 char 型
4.4 String类
String是一个类,它描述的是字符串。在Java代码当中,所有字符串常量(字符串字面量)都是 String类的一个实例对象。并且,字符串一旦创建,则不可修改! 不可修改其长度,不可修改其内容 。所以将来对字符串内容的改变,不能在原地改,只能重新创建一个字符串。
public class Sample {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "ab" + "dc";
//上述代码一共有几个字符串?
//四个"abc" "ab" "dc" "abdc"
}
}
- char charAt(int index):获取指定角标index处的字符
- int indexOf(int ch):获取指定字符(编码)在字符串中第一次(从左到右)出现的地方返回的是角标。如果是-1 表示不存在
- int lastIndexOf(int ch):获取指定字符(编码)在字符串中第一次(从右到做)出现的地方返回的是角标
- int indexOf(String str):获取指定字符串在本字符串中第一次(从左到右)出现的地方返回的是角标
- int lastIndexOf(String str):获取指定字符串在本字符串中第一次(从右到左)出现的地方返回的是角标
- int length():获取字符串的长度(字符的个数)
- String[] split(String regex):将字符串按照regex的定义进行切割(regex指的是正则表达式)
- String substring(int beginIndex):截取一段子字符串,从beginIndex开始到结尾
- String substring(int beginIndex, int endIndex):截取一段子字符串,从beginIndex开始到 endIndex(不包含)
从字符串中获取字符
方法 s.charAt(index)可用于提取字符串 s 中的某个特定字符,其中下标 index 的取值 范围在 0 ~ s.length()-1之间。例如,message.charAt(0)返回字符 W, 如图 4-1 所示。注意,字符串中第一个字符的下标值是0。
连接字符串
可以使用 concat 方法连接两个字符串,例如,String s3 = s1.concat(s2);等价于String s3 = s1 + s2;加号(+)也可用于连接数字和字符串。在这种情况下,先将数字转换成字 符串,然后再进行连接。注意,若要用加号实现连接功能,至少要有一个操作数必须为字符 串。如果操作数之一不是字符串(比如,一个数字),非字符串值转换为字符串,并与另外 一个字符串连接。
从控制台读取字符串
next()方法读取以空白字符结束的字符串(即 ' '、'\t' 、'\f'、'\r' 或 '\n')。可以使 用 nextLine() 方法读取一整行文本。nextLine()方法读取以按下回车键为结束标志的字符串。
重要警告:为了避免输入错误,不要在 nextByte()、nextShort()、nextlnt()、nextLong()、nextFloat()、nextDouble() 和 next()之后使用 nextLine()
从控制台读取字符
为了从控制台读取字符,调用 nextLine()方法读取一个字符串,然后在字符串上调用 charAt(0)来返回一个字符.
- int compareTo(String anotherString):按照字典顺序比较两个字符串的大小
- boolean contains(String another):判断当前字符串中是否包含指定字符串another
- boolean equals(String another):比较当前字符串与指定字符串的内容是否相同
- boolean isEmpty():判断当前字符串是否为空,length() == 0
- boolean startsWith(String prefix):判断该字符串是否以prefix开头
- boolean endsWith(String suwix):判断该字符串是否已suwix结尾
- String toLowerCase():将字符串中所有的英文字母全部变为小写
- String toUpperCase():将字符串中所有的英文字母全部变为大写
- String trim():将字符串中两端的多余空格进行删除
- String replace(char oldCh,char newCh):将字符串中oldCh字符替换成newCh字符
import java.util.Random;
public class Sample {
public static void main(String[] args) {
String str = "banana orange apple watermelon";
System.out.println(str.charAt(1)); //'a'
System.out.println(str.indexOf('o')); //7
System.out.println(str.lastIndexOf(97));//21
System.out.println(str.length());
System.out.println(str.substring(6));
System.out.println(str.substring(9,13));
String[] arr = str.split(" ");
System.out.println(arr[2]);
String s1 = "abc";
String s2 = "abe";
System.out.println(s1.compareTo(s2));
//结果<0 s1在s2之前 ==0 s1和s2一样 >0 s1在s2之后
System.out.println("hehe".compareTo("hehe"));
System.out.println("abcbc".contains("bcb"));
System.out.println("lala".equals("lala"));
String s3 = "大桥未久.avi";
System.out.println(s3.endsWith(".avi"));
System.out.println(s3.startsWith("大桥未久"));
String s4 = "Happy Boy Happy Girl";
System.out.println(s4.toLowerCase());
System.out.println(s4.toUpperCase());
System.out.println(s4);
System.out.println(" 123123 321321 ".trim());
String s5 = "旺财是只狗,旺财咋叫?旺财来叫一个~";
System.out.println(s5.replace('狗','猫'));
System.out.println(s5.replace("旺财","小强"));
}
}
如何删除字符串中左右两端出现的空格,不用trim
public class Sample {
public static void main(String[] args) {
String str = " 123123123 12123 ";
//去空格后"123123123 12123"
int l = 0;
int r = str.length() - 1;
while (str.charAt(l) == ' ') {
l++;
}
while (str.charAt(r) == ' ') {
r--;
}
System.out.println("[" + str.substring(l,r + 1) + "]");
}
}
在字符串"abcbcbcbcbcbc"中统计"bcb"出现的次数
public class Sample {
public static void main(String[] args) {
//最好的算法KMP算法
String s1 = "abcbcbcbcbcbc";
String s2 = "bcb"; //贪心算法 5个
int count = 0;
for (int i = 0; i < s1.length() - s2.length() + 1; i++) {
if (s1.charAt(i) == s2.charAt(0)) {
if (s2.equals(s1.substring(i,i + s2.length()))) {
count++;
}
}
}
System.out.println(count);
//非贪心算法 3个
/*
String temp = s1;
int count = 0;
while (true) {
int index = temp.indexOf(s2);
if (index == -1) {
break;
}
count++;
temp = temp.substring(index + s2.length());
}
System.out.println(count);
*/
}
}
查找两个字符串中最长的公共子串
public class homework03 {
public static void main(String[] args) {
//1.输入两个字符串
String s1 = "我喜欢你手里的蛋糕";
String s2 = "我喜欢你的东西";
//2.找字符串的规律
for (int len = s2.length(); len > 0; len--) {
for ( int l = 0, r = len - 1; r < s2.length(); l++,r++) {
String temp = s2.substring(l, r + 1);
//3.判断找出的temp是否为s1的子串
if (s1.contains(temp)) {
System.out.println(temp);
return;//直接结束程序
}
}
}
}
}
4.5 Character类
Character它是char基本数据类型的 包装类 ,有这么几个静态方法我可目前可以使用到的
- dstatic boolean isDigit(char ch):判断字符是否是数字
- static boolean isLetter(char ch):判断字符是否是字母
- static boolean isLetterOrDigit(char ch):判断字符是否是数字或字母
- static boolean isLowerCase(char ch):判断是否是小写字母
- static boolean isUpperCase(char ch):判断是否是大写字母
- static boolean isSpaceChar(char ch):判断是否空白字母(空格 制表符 回车)
System.out.println("isDigit('a') is " + Character.isDigitC('a')); System.out.println("isLetter('a') is " + Character.isLetter('a')); System.out.println("isLowerCase('a') is " + Character.isLowerCase('a')); System.out.println("isUpperCase('a') is " + Character.!sUpperCase('a')); System.out.println("toLowerCase('T') is " + Character.toLowerCase('T')); System.out.println("toUpperCase('q') is " + Character.toUpperCase('q'));
显示:
isDigit('a') is false
isLetter('a') is true
isLowerCase('a') is true
isUpperCase('a') is false
toLowerCase('T') is t
toUpperCase('q') is Q
将十六进制数字转为十进制
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个十六进制的数字:");
//0~9 A~F
String hex = input.nextLine().toUpperCase();
if (hex.length() == 0) {
System.out.println("没有任何输入!");
return;//程序直接结束
}
for (int i = 0; i < hex.length(); i++) {
char ch = hex.charAt(i);
if (Character.isDigit(ch) || Character.isLetter(ch)) {
if (Character.isLetter(ch) && (ch < 'A' || ch > 'F')) {
System.out.println("非法字符" + ch);
return;
}
} else {
System.out.println("非法字符" + ch);
return;
}
}
int sum = 0;
for (int i = hex.length() - 1; i >= 0; i--) {
char ch = hex.charAt(i);
if (Character.isDigit(ch)) {
//'1' ? 1
sum = sum + (int)Math.pow(16 , hex.length() - i - 1) * (ch - 48);
} else {
//'A' - 65 + 10 -> 10
sum = sum + (int)Math.pow(16 , hex.length() - i - 1) * (ch - 55);
}
}
System.out.println(sum);
}
}