04-数学函数、字符和字符串
-
4.1 引言
- 介绍数学函数、字符和字符串对象,并使用他们来开发程序。
-
4.2 常用数学函数
- 4.2.1 三角函数方法
Math类中的三角函数方法 方法 描述 sin(radians) 返回以弧度为单位的角度的三角正弦函数值 cos(radians) 返回以弧度为单位的角度的三角余弦函数值 tan(radians) 返回以弧度为单位的角度的三角正切函数值 toRadians(degrees) 将以度为单位的角度值转换为以弧度表示 toDegrees(radians) 将以弧度为单位的角度值转换为以度表示 asin(a) 返回以弧度为单位的角度的反三角正弦函数值 acos(a) 返回以弧度为单位的角度的反三角余弦函数值 atan(a) 返回以弧度为单位的角度的反三角正切函数值 package chapter04; public class MathMethod { public static void main(String[] args){ System.out.println(Math.toDegrees(Math.PI)); System.out.println(Math.toRadians(30)); System.out.println(Math.sin(0)); System.out.println(Math.sin(Math.toRadians(270))); System.out.println(Math.sin(Math.PI / 6)); System.out.println(Math.sin(Math.PI / 2)); System.out.println(Math.cos(0)); System.out.println(Math.cos(Math.PI / 6)); System.out.println(Math.cos(Math.PI / 2)); System.out.println(Math.asin(0.5)); System.out.println(Math.acos(0.5)); System.out.println(Math.atan(1.0)); } }
结果显示:
180.0 0.5235987755982988 0.0 -1.0 0.49999999999999994 1.0 1.0 0.8660254037844387 6.123233995736766E-17 0.5235987755982989 1.0471975511965979 0.7853981633974483 Process finished with exit code 0
- 4.2.2 指数函数方法
Math类中的指数函数方法
方法 描述 exp(x) 返回e的x次方(e^x) log(x) 返回x的自然对数(Inx=loge(x) log10(x) 返回x的以10为底的对数(log10(x)) pow(a,b) 返回a的b次方(a^b) sqrt(x) 对于x≥0的数字,返回x的平方根 package chapter04; public class MathMethod { public static void main(String[] args){ System.out.println(Math.exp(3.5)); System.out.println(Math.log(3.5)); System.out.println(Math.log10(3.5)); System.out.println(Math.pow(2,3)); System.out.println(Math.pow(3,2)); System.out.println(Math.pow(4.5,2.5)); System.out.println(Math.sqrt(4)); System.out.println(Math.sqrt(10.5)); } }
结果显示:
33.11545195869231 1.252762968495368 0.5440680443502757 8.0 9.0 42.95673695708276 2.0 3.24037034920393 Process finished with exit code 0
- 4.2.3 取整方法
Math类中的取整方法
方法 描述 ceil(x) x向上取整为它最近的整数。该整数作为一个双精度值返回 floor(x) x向下取整为它最近的整数。该整数作为一个双精度值返回 rint(x) x取整为它最接近的整数。如果x与两个整数的距离相等,偶数的整数作为一个双精度值返回 round(x) 如果x是单精度数,返回(int)Math.floor(x+0.5);如果x是双精度数,返回(long)Math.floor(x+0.5) package chapter04; public class MathMethod { public static void main(String[] args){ System.out.println(Math.ceil(2.1)); System.out.println(Math.ceil(2.0)); System.out.println(Math.ceil(-2.0)); System.out.println(Math.ceil(-2.1)); System.out.println(Math.floor(2.1)); System.out.println(Math.floor(2.0)); System.out.println(Math.floor(-2.0)); System.out.println(Math.floor(-2.1)); System.out.println(Math.rint(2.1)); System.out.println(Math.rint(-2.0)); System.out.println(Math.rint(-2.1)); System.out.println(Math.rint(2.5)); System.out.println(Math.rint(4.5)); System.out.println(Math.rint(-2.5)); System.out.println(Math.round(2.6f));//return int System.out.println(Math.round(2.0));//return long System.out.println(Math.round(-2.0f));//returns int System.out.println(Math.round(-2.6));//return long System.out.println(Math.round(-2.4));//return long } }
结果显示:
3.0 2.0 -2.0 -2.0 2.0 2.0 -2.0 -3.0 2.0 -2.0 -2.0 2.0 4.0 -2.0 3 2 -2 -3 -2 Process finished with exit code 0
-
4.2.4 min、max和abs方法
- min和max方法用于返回两个数(int、long、float和double型)的最小值和最大值。
- abs函数以返回一个数(int、long、float和double)的绝对值。
package chapter04; public class MathMethod { public static void main(String[] args){ System.out.println(Math.max(2,3)); System.out.println(Math.min(2.5,4.6)); System.out.println(Math.max(Math.max(2.5,4.6),Math.min(3,5.6))); System.out.println(Math.abs(-2)); System.out.println(Math.abs(-2.1)); } }
结果显示:
3 2.5 4.6 2 2.1 Process finished with exit code 0
-
4.2.5 random方法
-
random()方法生成大于等于0.0且小于1.0的double型随机数。
(int)(Math.random() * 10);//返回0-9之前的一个随机整数 50 + (int)(Math.random() * 50);//返回50-99之间的一个随机数 a + Math.random() * b;//返回a——a+b之间的一个随机数,不包括a+b
-
-
4.2.6 示例学习:计算三角形的角度
-
提示用户输入三角形三个顶点的x和y坐标值,然后显示三个角。
package chapter04; import java.util.Scanner; public class ComputeAngles { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter three points: "); double x1 = input.nextDouble(); double y1 = input.nextDouble(); double x2 = input.nextDouble(); double y2 = input.nextDouble(); double x3 = input.nextDouble(); double y3 = input.nextDouble(); double a = Math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3)); double b = Math.sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3)); double c = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); double A = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c))); double B = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a * c))); double C = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * b * a))); System.out.println("The three angles are " + Math.round(A * 100) / 100.0 + " " + Math.round(B * 100) / 100.0 + " " + Math.round(C *100) / 100.0); } }
-
-
4.3 字符数据类型和操作
- 4.3.1 Unicode和ASCII码
-
字符数据类型用于表示单个字符。
-
字符串字面值必须括在双引号中。而字符字面值是括在单引号中的单个字符。因为“A”是一个字符串,而‘A’是一个字符。
-
自增和自减操作符也可用在char型变量上,这会得到该字符之前或之后的Unicode字符。例如,下面的语句显示字符b:
char ch = 'a'; System.out.println(++ch);
-
- 4.3.2 特殊字符的转义序列
- 反斜杠\被称为转义字符。它是一个特殊字符。
- 4.3.3 字符型数据与数字型数据之间的转换
-
char型数据可以转换成任意一种数值类型,反之亦然。将整数转换成char型数据时,只用到该数据的低十六位,其余部分都被忽略。
package chapter04; public class MathMethod { public static void main(String[] args){ char ch1 = (char)0XAB0041; System.out.println(ch1); char ch2 = (char)65.25; System.out.println(ch2); int i = (int)'A'; System.out.println(i); byte b = 'a'; int j = 'a'; byte bb = (byte)'\uFFF4'; int z = '2' + '3'; System.out.println("z is " + z); int x = 2 + 'a'; System.out.println("x is " + x); System.out.println(x + " is the Unicode for character " + (char)x); System.out.println("Chapter " + '2'); } }
结果显示:
A A 65 z is 101 x is 99 99 is the Unicode for characterc Chapter 2 Process finished with exit code 0
-
- 4.3.4 字符比较和测试
- 两个字符可以使用关系操作符进行比较,如同比较两个数字一样。
package chapter04; public class CharacterMethod { public static void main(String[] args){ System.out.println("isDidit('a') is " + Character.isDigit('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.isUpperCase('a')); System.out.println("toLowerCase('T') is " + Character.toLowerCase('T')); System.out.println("toUpperCase('q') is " + Character.toUpperCase('q')); } }
- 两个字符可以使用关系操作符进行比较,如同比较两个数字一样。
- 4.3.1 Unicode和ASCII码
-
4.4 String类型
字符串是一个字符序列。String类型不是基本类型,而是引用类型。
-
4.4.1 获取字符串长度
- 可以调用字符串的length()方法获取他的长度。
- 为方便起见,Java允许在不创建新变量的情况下,使用字符串字面值直接饮用字符串。这样“Welcome to Java”.length()是正确的,它返回15.注意,“”表示空字符串,并且.length()为0。
-
4.4.2 从字符串中获取字符
- 方法s.charAt(index)可用于提取字符串s中的某个特定字符。
- 在字符串s中越界访问字符是一个常见的程序设计错误。为了避免此类错误,要确保使用的下标不会超过s.length()-1。
-
4.4.3 连接字符串
- 加号(+)也可以用于连接字符串和数组。在这种情况下,先将数字转换成字符串,然后再进行连接。i,若要用加号实现连接的功能,至少要有一个操作数必须为字符串。
-
4.4.4 字符串的转换
- 方法trim()通过删除字符串两端的空白字符返回一个新字符串。字符‘ ’、\t、\f、\r或者\n被称为空白字符。
-
4.4.5 从控制台读取字符串
- 将使用方法next()、nextByte()、nextShort()、nextInt()、nextLong()、nextFloat()和nextDouble()的输入称为基于标记的输入,因为他们读取采用空白字符分隔的单个元素,而不是读取整行。nextLine()方法称为基于行的输入。
-
4.4.6 从控制台读取字符
- 调用nextLine()方法读取一个字符串,然后在字符串上调用charAt(0)来返回一个字符。
-
4.4.7 字符串比较
package chapter04; import java.util.Scanner; public class OrderTwoCities { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter the first city: "); String city1 = input.nextLine(); System.out.print("Enter the second city: "); String city2 = input.nextLine(); if (city1.compareTo(city2) < 0) System.out.println("The cities in alphabetical order are " + city1 + " " + city2); else System.out.println("The cities in alphabetical order are " + city2 + " " + city1); } }
-
4.4.8 获得子字符串
- 如果beginIndex为endIndex,substring(beginIndex,endIndex)返回一个长度为0的空字符串。如果beginIndex>endIndex,将发生运行错误。
-
4.4.9 获取字符串中的字符或者子串
-
4.4.10 字符串和数字间的转换
package chapter04; public class StringToInteger { public static void main(String[] args){ String intString = "123"; int intValue = Integer.parseInt(intString); System.out.println(intValue); String doubleString = "3.1415926"; double doubleValue = Double.parseDouble(doubleString); System.out.println(doubleValue); int number = 222; String s = number + ""; System.out.println(s); } }
-
-
4.5 示例学习
-
4.5.1 猜测生日
package chapter04; import java.util.Scanner; public class GuessBirthday { public static void main(String[] args){ String set1 = "1 3 5 7\n" + "9 11 13 15\n" + "17 19 21 23\n" + "25 27 29 31"; String set2 = "2 3 6 7\n" + "10 11 14 15\n" + "18 19 22 23\n" + "26 27 30 31"; String set3 = "4 5 6 7\n" + "12 13 14 15\n" + "20 21 22 23\n" + "28 29 30 31"; String set4 = "8 9 10 11\n" + "12 13 14 15\n" + "24 25 26 27\n" + "28 29 30 31"; String set5 = "16 17 18 19\n" + "20 21 22 23\n" + "24 25 26 27\n" + "28 29 30 31"; int day = 0; Scanner input = new Scanner(System.in); System.out.print("Is you birthday in Set1?\n"); System.out.print(set1); System.out.print("\nEnter 0 for No and 1 for Yes: "); int answer = input.nextInt(); if (answer == 1) day += 1; System.out.print("\nIs you birthday in Set2?\n"); System.out.print(set2); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 2; System.out.print("\nIs you birthday in Set3?\n"); System.out.print(set3); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 4; System.out.print("\nIs you birthday in Set4?\n"); System.out.print(set4); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 8; System.out.print("\nIs you birthday in Set5?\n"); System.out.print(set5); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 16; System.out.println("\nYour birthday is " + day + "!"); } }
-
4.5.2 将十六进制数转换为十进制
package chapter04; import java.util.Scanner; public class HexDigit2Dec { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a hex digit: "); String hexString = input.nextLine(); if (hexString.length() != 1){ System.out.println("You must enter exactly one character"); System.exit(1); } char ch = Character.toUpperCase(hexString.charAt(0)); if ('A' <= ch && ch <= 'F'){ int value = ch - 'A' + 10; System.out.println("The decimal value for hex digit " + ch + " is " + value); } else if (Character.isDigit(ch)){ System.out.println("The decimal value for hex digit " + ch + " is " + ch); } else{ System.out.println(ch + " is an invalid input"); } } }
-
4.5.3 使用字符串修改彩票程序
package chapter04; import java.util.Scanner; public class LotteryUsingStrings { public static void main(String[] args){ String lottery = "" + (int)(Math.random() * 10) + (int)(Math.random() * 10); Scanner input = new Scanner(System.in); System.out.print("Enter your lottery pick (two digits): "); String guess = input.nextLine(); char lotteryDigit1 = lottery.charAt(0); char lotteryDigit2 = lottery.charAt(1); char guessDigit1 = guess.charAt(0); char guessDigit2 = guess.charAt(1); System.out.println("The lottery number is " + lottery); if (guess.equals(lottery)) System.out.println("Exact match:you win $10,000"); else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) System.out.println("Match all digits:you win $3,000"); else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit2 || guessDigit2 == lotteryDigit1) System.out.println("Match one digit:yuo win $1,000"); else System.out.println("Sorry,no match"); } }
-
-
4.6 格式化控制台输出
-
可以使用System.out.printf方法在控制台上显示格式化输出。
-
printf中的f代表格式(format),暗示着方法将以某种格式打印。调用这个方法的语法是:
System.out.printf(format,item1,item2,...,itemk);
-
如果项需要比指定宽度更多的空间,宽度自动增加。例如,下面的代码:
System.out.printf("%3d#%2s#%4.2f\n",1234,"Java",51.6653);
结果显示:
1234#Java#51.67
-
如果要显示一个带有逗号的数字,可以在数字限定符前面添加一个逗号。
System.out.printf("%,8d %,10.1f\n",12345678,12345678.263);
结果显示:
12,345,678 12,345,678.3
-
如果要在数字前面添加0而不是空格来凑齐位数,可以在一个数字限定符前面添加0。
System.out.printf("%08d %08.1f\n",1234,5.63);
结果显示:
00001234 000005.6
-
默认情况下,输出是右对齐的。可以在格式限定符中放一个减号(-),指定该项在指定域中的出书是左对齐的。
System.out.printf("%-8d%-8s%-8.1f\n",1234,"Java",5.63);
结果显示:
1234 Java 5.6
-
条目与格式标识符必须在类型上严格匹配。对应于格式标识符%f或%e的条目必须是浮点型值,可以使用%.2f来指定一个小数点后两位的浮点数值,而是用%0.2f是不正确 。
-
package chapter04;
public class FormatDemo {
public static void main(String[] args){
System.out.printf("%-10s%-10s%-10s%-10s%-10s\n","Degrees","Radians","Sine","Cosine","Tangent");
int degrees = 30;
double radians = Math.toRadians(degrees);
System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n",degrees,radians,Math.sin(radians),Math.cos(radians),Math.tan(radians));
degrees = 60;
radians = Math.toRadians(degrees);
System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n",degrees,radians,Math.sin(radians),Math.cos(radians),Math.tan(radians));
}
}
结果显示:
Degrees Radians Sine Cosine Tangent
30 0.5236 0.5000 0.8660 0.5774
60 1.0472 0.8660 0.5000 1.7321
Process finished with exit code 0
- 编程小习题
- 1、
package chapter04; import java.util.Scanner; public class Code_01 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter the length from the center to a vertex: "); double r = input.nextDouble(); double s = 2 * r * Math.sin(Math.PI / 5); double area = 5 * s * s / (4 * Math.tan(Math.PI / 5)); System.out.printf("The area of the pentagon is %.2f",area); } }
- 2、
package chapter04; public class Code_06 { public static void main(String[] args){ double x1, y1, x2, y2, x3, y3; double angleA,angleB,angleC,alpha; double a,b,c; alpha = Math.random() * (2 * Math.PI); x1 = 40 * Math.cos(alpha); y1 = 40 * Math.sin(alpha); alpha = Math.random() * (2 * Math.PI); x2 = 40 * Math.cos(alpha); y2 = 40 * Math.sin(alpha); alpha = Math.random() * (2 * Math.PI); x3 = 40 * Math.cos(alpha); y3 = 40 * Math.sin(alpha); a = Math.sqrt(Math.pow(x1 - x2, 2)+Math.pow(y1 - y2, 2)); b = Math.sqrt(Math.pow(x1 - x3, 2)+Math.pow(y1 - y3, 2)); c = Math.sqrt(Math.pow(x3 - x2, 2)+Math.pow(y3 - y2, 2)); angleA = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c))); angleB = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a * c))); angleC = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * b * a))); System.out.printf("The first angle in degree is %.2f\n", angleA); System.out.printf("The second angle in degree is %.2f\n", angleB); System.out.printf("The third angle in degree is %.2f", angleC); } }
- 3、
package chapter04; import java.util.Scanner; public class Code_08 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter an ASCII code : "); int number = input.nextInt(); System.out.println("The character for ASCII code " + number + " is " + (char)number); } }
- 4、
package chapter04; import java.util.Scanner; public class Code_09 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); String str = input.nextLine(); char character = str.charAt(0); System.out.println("The Unicode for the character " + character + " is " + (int)character); } }
- 5、
package chapter04; import java.util.Scanner; public class Code_15 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a letter: "); String str = input.nextLine(); char letter = str.toUpperCase().charAt(0); if (letter == 'A' || letter == 'B' || letter == 'C') System.out.println("The corresponding number is 2"); else if (letter == 'D' || letter == 'E' || letter == 'F') System.out.println("The corresponding number is 3"); else if (letter == 'G' || letter == 'H' || letter == 'I') System.out.println("The corresponding number is 4"); else if (letter == 'J' || letter == 'K' || letter == 'L') System.out.println("The corresponding number is 5"); else if (letter == 'M' || letter == 'N' || letter == 'O') System.out.println("The corresponding number is 6"); else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') System.out.println("The corresponding number is 7"); else if (letter == 'T' || letter == 'U' || letter == 'V') System.out.println("The corresponding number is 8"); else System.out.println("The corresponding number is 9"); } }
- 6、
package chapter04; public class Code_16 { public static void main(String [] args){ System.out.println((char) ((int)(Math.random() * 26) + 65)); } }
- 7、
package chapter04; import java.util.*; public class Code_21 { public static void main(String[] args){ String ssnString; System.out.print("Enter a SSN: "); Scanner input = new Scanner(System.in); ssnString = input.nextLine(); if(ssnString.length() == 11) { if(Character.isDigit(ssnString.charAt(0)) && Character.isDigit(ssnString.charAt(1)) && Character.isDigit(ssnString.charAt(2)) && ssnString.charAt(3) == '-' && Character.isDigit(ssnString.charAt(4)) && Character.isDigit(ssnString.charAt(5)) && ssnString.charAt(6) == '-' && Character.isDigit(ssnString.charAt(7)) && Character.isDigit(ssnString.charAt(8)) && Character.isDigit(ssnString.charAt(9)) && Character.isDigit(ssnString.charAt(10))) System.out.println(ssnString + " is a valid social security number"); else System.out.println(ssnString + " is an invalid social security number"); } else System.out.println(ssnString + " is an invalid social security number"); input.close(); } }
- 8、
package chapter04; import java.util.*; public class Code_22 { public static void main(String[] args) { String string1,string2; System.out.print("Enter string s1: "); Scanner input = new Scanner(System.in); string1 = input.nextLine(); System.out.print("Enter string s2: "); string2 = input.nextLine(); System.out.println(string1.contains(string2) ?string2 + " is a substring of " + string1 :string2 + " is not a substring of " + string1); input.close(); } }
- 9、
package chapter04; import java.util.*; public class Code_24 { public static void main(String[] args) { String city1,city2,city3; Scanner inputScanner = new Scanner(System.in); System.out.print("Enter the first city: "); city1 = inputScanner.nextLine(); System.out.print("Enter the second city: "); city2 = inputScanner.nextLine(); System.out.print("Enter the third city: "); city3 = inputScanner.nextLine(); if(city1.compareTo(city2) > 0) // city1 > city2 { if(city2.compareTo(city3) > 0) // city2 > city3 System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3); else //city2 < city3 { if(city1.compareTo(city3) > 0) // city1 > city3 System.out.println("The three cities in alphabetical order are " + city2 + " " + city3 + " " + city1); else // city1 < city3 System.out.println("The three cities in alphabetical order are " + city2 + " " + city1 + " " + city3); } } else // city1 < city2 { if(city1.compareTo(city3) > 0) // city1 > city3 System.out.println("The three cities in alphabetical order are " + city3 + " " + city1 + " " + city2); else //city1 < city3 { if(city2.compareTo(city3) > 0) // city2 > city3 System.out.println("The three cities in alphabetical order are " + city1 + " " + city3 + " " + city2); else // city2 < city3 System.out.println("The three cities in alphabetical order are " + city1 + " " + city2 + " " + city3); } } inputScanner.close(); } }
- 10、
package chapter04; public class Code_25 { public static void main(String[] args) { char char1,char2,char3,char4,char5,char6,char7; char1 = (char)(65 + (int)(Math.random() * 26)); char2 = (char)(65 + (int)(Math.random() * 26)); char3 = (char)(65 + (int)(Math.random() * 26)); char4 = (char)(48 + (int)(Math.random() * 10)); char5 = (char)(48 + (int)(Math.random() * 10)); char6 = (char)(48 + (int)(Math.random() * 10)); char7 = (char)(48 + (int)(Math.random() * 10)); System.out.println("The vehicle plate numbers is " + char1+char2+char3+char4+char5+char6+char7); } }
- 1、