Java学习笔记(4)Mathematical Functions, Characters, and Strings

4.2 Common Mathematical Functions

两个预定义常量:Math.PI,Math.E


4.2.1 Trigonometric Methods

Method                Description

sin(radians)           Returns the trigonometric sine of an angle in radians.

cos(radians)          Returns the trigonometric cosine of an angle in radians.

tan(radians)          Returns the trigonometric tangent of an angle in radians.

toRadians(degree)    Returns the angle in radians for the angle in degree.

toDegree(radians)    Returns the angle in degrees for the angle in radians.

asin(a)               Returns the angle in radians for the inverse of sine.

acos(a)              Returns the angle in radians for the inverse of cosine.

atan(a)              Returns the angle in radians for the inverse of tangent.

 

The parameter for sin,cos, andtanis an angle in radians. The return value forasinacos, andatanis a degree in radians in the range between -pi/2 and pi/2. One degree is equal to pi/180 in radians, 90 degrees is equal to pi/2 in radians, and 30 degrees is equal to pi/6 in radians.

For example,

Math.toDegrees(Math.PI / 2) returns90.0

Math.toRadians(30) returns0.5236(same as π/6)

Math.sin(0) returns0.0

Math.sin(Math.toRadians(270)) returns-1.0

Math.sin(Math.PI / 6) returns0.5

Math.sin(Math.PI / 2) returns1.0

Math.cos(0) returns1.0

Math.cos(Math.PI / 6) returns0.866

Math.cos(Math.PI / 2) returns0

Math.asin(0.5) returns0.523598333(same as π/6)

Math.acos(0.5) returns1.0472(same as π/3)

Math.atan(1.0) returns0.785398(same as π/4)


4.2.2 Exponent Methods

Method      Description

exp(x)     Returns e raised to power of x (ex).

log(x)     Returns the natural logarithm of x (ln(x) = loge(x)).

log10(x)   Returns the base 10 logarithm of x (log10(x)).

pow(a, b)  Returns a raised to the power of b (ab).

sqrt(x)    Returns the square root of x (2x) for x 7 = 0.

 

For example,

 

Math.exp(1) returns2.71828

Math.log(Math.E) returns 1.0

Math.log10(10) returns1.0

Math.pow(2, 3) returns8.0

Math.pow(3, 2) returns9.0

Math.pow(4.5, 2.5) returns22.91765

Math.sqrt(4) returns2.0

Math.sqrt(10.5) returns4.24


4.2.3 The Rounding Methods

Method Description

ceil(x)      x is rounded up to its nearest integer. This integer is returned as a double value.

floor(x)    x is rounded down to its nearest integer. This integer is returned as a double value.

rint(x)     x is rounded up to its nearest integer. If x is equally close to two integers, the even one is returned as a double value.

round(x)    Returns (int)Math.floor(x + 0.5) if x is a float and returns (long)Math.floor(x + 0.5) if x is a double.

 

For example,

 

Math.ceil(2.1) returns4.0

Math.ceil(2.0) returns2.0

Math.ceil(-2.0) returns-2.0

Math.ceil(-2.1) returns-2.0

Math.floor(2.1) returns2.0

Math.floor(2.0) returns2.0

Math.floor(-2.0) returns–2.0

Math.floor(-2.1) returns-4.0

Math.rint(2.1) returns2.0

Math.rint(-2.0) returns–2.0

Math.rint(-2.1) returns-2.0

Math.rint(2.5) returns2.0

Math.rint(4.5) returns4.0

Math.rint(-2.5) returns-2.0

Math.round(2.6f) returns3// Returns int

Math.round(2.0) returns2// Returns long

Math.round(-2.0f) returns-2// Returns int

Math.round(-2.6) returns-3// Returns long

Math.round(-2.4) returns-2// Returns long

 

4.2.4 The min, max, and abs Methods

The min and maxmethods return the minimum and maximum numbers of two numbers (intlong,float, ordouble). For example,max(4.4, 5.0)returns 5.0, andmin(3, 2) returns2.

The abs method returns the absolute value of the number (int,long,float, ordouble).


4.2.5 The random Method

产生一个0.0到 1.0之间的随机数(0 <= Math.random() < 1.0),类型是double。

例如:

更一般地,


4.3.1 Unicode and ASCII code

Java字符采用Unicode格式,它是16位的字符编码方案,可以表示世界上的大部分常用文字,包括中文。

Unicode是双字节的,以\u开头,后面跟上4个16进制数字,也就是从‘\u0000’到‘\uFFFF’。所以Unicode可以表示65535 + 1个字符。

注意一定要写满4个数字,所以‘\u0’, ‘\u00’, ‘\u000’的写法都是错误的。

The Unicodes for the Greek letters a b g are \u03b1 \u03b2 \u03b4.

Most computers use ASCII (American Standard Code for Information Interchange), an 8-bit encoding scheme for representing all uppercase and lowercase letters, digits, punctuation marks, and control characters. Unicode includes ASCII code, with \u0000 to \u007Fcorresponding to the 128 ASCII characters. Table 4.4 shows the ASCII code for some commonly used characters. Appendix B, ‘The ASCII Character Set,’ gives a complete list of ASCII characters and their decimal and hexadecimal codes. 

Characters Code Value in Decimal Unicode Value

'0' to '9'48 to 57 \u0030 to \u0039

'A' to 'Z'65 to 90 \u0041 to \u005A

'a' to 'z'97 to 122 \u0061 to \u007A


4.3.2 生成随机字符

Java字符采用的是Unicode编码,取值从0-65535,所以只要随机生成一个该范围内的整数,转换类型之后就是字符了.

由于 0 <= Math.random() < 1.0, 所以可以按照下式生成随机字符:

     (int)(Math.random() * (65535 + 1))

注意随机数取不到1,所以65535需要+1


4.3.3 随机生成小写字母

字母从 ‘a’, ‘b’, ‘c’, ..., 到 ‘z’ ,它们的Unicode值是递增的,所以随机小写字母可以这么生成:

(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)

考虑到char类型在算术运算的时候会被自动转成int,所以上式可以简写成:

(char)('a' + Math.random() * ('z' - 'a' + 1))

 

4.3.4 生成某区间的随机字符

更一般地,要生成 ch1 和 ch2 之间的随机字符(含ch1和ch2,且 ch1 < ch2),可以按照下式生成:

(char)(ch1 + Math.random() * (ch2 – ch1 + 1))

字符类型

char letter = 'A'; (ASCII)       

char numChar = '4'; (ASCII)

char letter = '\u0041'; (Unicode)

char numChar = '\u0034'; (Unicode)

自增自减运算符可以用在char类型上。例如,下面的代码将会显示一个b字母:

    char ch = 'a';

    System.out.println(++ch);

 

4.3.5 转义字符

Description       Escape Sequence Unicode

退格                 \b        \u0008

Tab                  \t        \u0009

换行                 \n        \u000A

回车                 \r        \u000D

反斜杠               \\        \u005C

单引号                \'      \u0027

双引号                \"       \u0022

 

4.3.6 字符和数值类型的相互转换

int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

 

4.4 字符串类型

char只能用来表示单个字符,如果需要表示一串字符,可以使用String。例如: 

String message = "Welcome to Java";

String其实是Java预先定义的一个类,和System或者JOptionPane类一样,String类不是基本类型,它是一种引用类型(reference type)。

关于引用类型的进一步描述会在后面的章节展开,这里你可以简单把String当作一种类型来使用。

 

4.4.1 字符连接

// 三个字符串连接在一起

String message = "Welcome " + "to " + "Java";

// 字符串后面连上数字

String s = “Chapter” + 2; // s变为Chapter2

// 字符串后面连上字母

String s1 = “Supplement” + ‘B’; // s1变为SupplementB


4.4.2字符串函数

 

 

4.4.3 Comparing Strings

LISTING4.2OrderTwoCities.java

 import java.util.Scanner;

 public class OrderTwoCities {
	 public static void main(String[] args) {
		 Scanner input = new Scanner(System.in);

		 // Prompt the user to enter two cities
		 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.4 例题:猜生日

下面有5个表,逐一提问用户生日是否在每一个表中,最后可以猜出用户生日。

某次执行结果

 

确认对话框

int option = JOptionPane.showConfirmDialog(null, "Continue");

返回值有三种:

Yes按钮:JOptionPane.YES_OPTION (0)

No按钮:JOptionPane.NO_OPTION (1)

Cancel按钮:JOptionPane.CANCEL_OPTION (2)


代码:

import javax.swing.JOptionPane;
public class JavaApplication2 {
    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;
        //挨个表问过去,5个表权重分别为1,2,4,8,16,求和结果即为生日
        int answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set1);
        if (answer == JOptionPane.YES_OPTION)
            day += 1;
        answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set2);
        if (answer == JOptionPane.YES_OPTION)
            day += 2;
        answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set3);
        if (answer == JOptionPane.YES_OPTION)
            day += 4;
        answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set4);
        if (answer == JOptionPane.YES_OPTION)
            day += 8;
        answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set5);
        if (answer == JOptionPane.YES_OPTION)
            day += 16;
        JOptionPane.showMessageDialog(null, "Your birthday is " + day + "!");
    }
}


4.5 Formatting Console Output

You can use the System.out.printfmethod to display formatted output on the

Console.

System.out.printf(format, item1, item2, ..., itemk)

where format is a string that may consist of substrings and format specifiers.Aformat specifier  specifies how an item should be displayed. An item may be a numeric value, a character, a Boolean value, or a string. A simple format specifier consists of a percent sign (%) followed by a conversion code.

Format Specifier        Output                                     Example

%b                  a Boolean value                               true or false

%c                  a character                                    ‘a’

%d                 a decimal integer                               200

%f                a floating-point number                          45.460000

%e               a number in standard scientific notation            4.556000e+01

%s                     a string                                    “Java is cool”

Example :

%5c

Output the character and add four spaces before the character item, because the width is 5.

%6b

Output the Boolean value and add one space before the false value and two spaces before the true value.

%5d

Output the integer item with width at least 5. If the number of digits in the item is 6 5, add spaces before the number. If the number of digits in the item is 7 5, the width is automatically increased.

%10.2f

Output the floating-point item with width at least 10 including a decimal point and two digits after the point. Thus, there are 7 digits allocated before the decimal point. If the number of digits before the decimal point in the item is 6 7, add spaces before the number. If the number of digits before the decimal point in the item is 7 7, the width is automatically increased.

%10.2e

Output the floating-point item with width at least 10 including a decimal point, two digits after the point and the exponent part. If the displayed number in scientific notation has width less than 10, add spaces before the number.

%12s

Output the string with width at least 12 characters. If the string item has fewer than 12 characters, add spaces before the string. If the string item has more than 12 characters, the width is automatically increased.

 

If an item requires more spaces than the specified width, the width is automatically increased. For example, the following code

System.out.printf("%3d#%2s#%4.2f\n",1234,"Java", 51.6653);

Displays:

1234#Java#51.67

The specified width for int item1234 is 3, which is smaller than its actual size4. The width is automatically increased to4. The specified width for string itemJava is 2, which is smaller than its actual size4. The width is automatically increased to4. The specified width fordouble item 51.6653is 4, but it needs width 5 to display 51.67, so the width is automatically increased to5.

By default, the output is right justified. You can put the minus sign (-) in the format specifier to specify that the item is left justified in the output within the specified field. For example, the following statements

System.out.printf("%8d%8s%8.1f\n",1234,"Java", 5.63);

System.out.printf("%-8d%-8s%-8.1f \n",1234,"Java", 5.63);

 

LISTING4.6 FormatDemo.java

 public class FormatDemo {
	 public static void main(String[] args) {
		 // Display the header of the table
		 System.out.printf("%-10s%-10s%-10s%-10s%-10s\n", "Degrees",
			 "Radians", "Sine", "Cosine", "Tangent");

		 // Display values for 30 degrees
		 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));

		 // Display values for 60 degrees
		 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.5773

60         1.0472    0.8660   0.5000   1.7320

 

The statement in lines 4–5 displays the column names of the table. The column names are strings. Each string is displayed using the specifier%-10s, which left-justifies the string. The statement in lines 10–12 displays the degrees as an integer and four float values. The integer is displayed using the specifier%-10dand each float is displayed using the specifier%-10.4f, which specifies four digits after the decimal point.


CHAPTER 4 SUMMARY

1. Java provides the mathematical methodssin,cos,tan,asin,acos,atan,toRadianstoDegree,exp,log,log10,pow,sqrt,cell,floor,rint,round,min,maxabs, and randomin theMath class for performing mathematical functions.

2. The character typecharrepresents a single character.

3. An escape sequence consists of a backslash (\) followed by a character or a combination of digits.

4. The character \is called the escape character.

5. The characters ' ',\t,\f,\r, and\nare known as the whitespace characters.

6. Characters can be compared based on their Unicode using the relational operators.

7. The Characterclass contains the methodsisDigit,isLetter,isLetterOrDigitisLowerCase,isUpperCasefor testing whether a character is a digit, letter, lowercase, and uppercase. It also contains thetoLowerCaseand toUpperCase methods for returning a lowercase or uppercase letter.

8. A string is a sequence of characters. A string value is enclosed in matching double quotes ("). A character value is enclosed in matching single quotes (').

9. Strings are objects in Java. A method that can only be invoked from a specific object is called aninstance method. A non-instance method is called a static method, which can be invoked without using an object.

10. You can get the length of a string by invoking itslength()method, retrieve a character at the specified index in the string using thecharAt(index)method, and use theindexOf and lastIndexOfmethods to find a character or a substring in a string.

11. You can use theconcatmethod to concatenate two strings, or the plus (+) operator to concatenate two or more strings.

12. You can use thesubstringmethod to obtain a substring from the string.

13. You can use theequalsand compareTomethods to compare strings. Theequals method returnstrueif two strings are equal, andfalseif they are not equal. The compareTomethod returns0, a positive integer, or a negative integer, depending on whether one string is equal to, greater than, or less than the other string.

14. The printfmethod can be used to display a formatted output using format

specifiers.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值