Intro to Java Programming(Liang.10th)--04

4.2 Common Mathematical Functions

Java provides many useful methods in the Math class for performing common mathematical functions
You can use these constants as Math.PI and Math.E in any program.

4.2.1 Trigonometric Methods

The parameter for sin, cos, and tan is an angle in radians. The return value for asin,
acos, and atan
is a degree in radians in the range between -p/2 and p/2. One degree is
equal to p/180 in radians, 90 degrees is equal to p/2 in radians, and 30 degrees is equal to
p/6 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.

4.2.2 Exponent Methods

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.
  1. For example,
    Math.exp(1) returns 2.71828
    Math.log(Math.E) returns 1.0
    Math.log10(10) returns 1.0
    Math.pow(2, 3) returns 8.0
    Math.pow(3, 2) returns 9.0
    Math.pow(4.5, 2.5) returns 22.91765
    Math.sqrt(4) returns 2.0
    Math.sqrt(10.5)

4.2.3 The Rounding Methods

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.
  1. For example,
    Math.ceil(2.1) returns 4.0
    Math.ceil(2.0) returns 2.0
    Math.ceil(-2.0) returns -2.0
    Math.ceil(-2.1) returns -2.0
    Math.floor(2.1) returns 2.0
    Math.floor(2.0) returns 2.0
    Math.floor(-2.0) returns –2.0
    Math.floor(-2.1) returns -4.0
    Math.rint(2.1) returns 2.0
    Math.rint(-2.0) returns –2.0
    Math.rint(-2.1) returns -2.0
    Math.rint(2.5) returns 2.0
    Math.rint(4.5) returns 4.0
    Math.rint(-2.5) returns -2.0
    Math.round(2.6f) returns 3 // Returns int
    Math.round(2.0) returns 2 // 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 max methods return the minimum and maximum numbers of two numbers (int,
long, float, or double). For example, max(4.4, 5.0) returns 5.0, and min(3, 2)
returns 2
The abs method returns the absolute value of the number (int, long, float, or double).
For example,
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 4.0
Math.min(2.5, 4.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1

4.2.5 The random Method

This method generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() <1.0).

  1. (int)(Math.random() * 10)
    Returns a random integer
    between 0 and 9.
  2. 50 + (int)(Math.random() * 50)
    Returns a random integer
    between 50 and 99.

4.3 Character Data Type and Operations

A character data type represents a single character.

4.3.1 Unicode and ASCII code

Computers use binary numbers internally. A character is stored in a computer as a sequence of 0s and 1s. Mapping a character to its binary representation is called encoding .

Java supports Unicode, an encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode was originally designed as a 16-bit character encoding. The primitive data type char was intended to take advantage of this design by providing a simple data type that could hold any character. However, it turned out that the 65,536 characters possible in a 16-bit encoding are not sufficient to represent all the characters in the world. The Unicode standard therefore has been extended to allow up to 1,112,064 characters. Those characters that go beyond the original 16-bit limit are called supplementary characters. Java supports the supplementary characters. The processing and representing of supplementary characters
are beyond the scope of this book. For simplicity, this book considers only the original 16-bit
Unicode characters.
These characters can be stored in a char type variable.

A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal digits that
run from \u0000 to \uFFFF.For example, the English word welcome is translated into Chinese using two characters, . The Unicodes of these two characters are \u6B22\u8FCE. 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 \u007F corresponding to the 128 ASCII characters.
The increment and decrement operators can also be used on char variables to get the
next or preceding Unicode character
.

4.3.2 Escape Sequences for Special Characters

4.3.3 Casting between char and Numeric Types

A char can be cast into any numeric type, and vice versa. When an integer is cast into a char,
only its lower 16 bits of data are used; the other part is ignored.
When a floating-point value is cast into a char, the floating-point value is first cast into an
int, which is then cast into a char.
When a char is cast into a numeric type, the character’s Unicode is cast into the specified
numeric type.

4.3.4 Comparing and Testing Characters

isDigit(ch)     Returns true if the specified character is a digit.
isLetter(ch)    Returns true if the specified character is a letter.
isLetterOfDigit(ch) Returns true if the specified character is a letter or digit.
isLowerCase(ch) Returns true if the specified character is a lowercase letter.
isUpperCase(ch) Returns true if the specified character is an uppercase letter.
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.

System.out.println("isDigit(‘a’) is " + Character.isDigit(‘a’));
display:
isDigit(‘a’) is false.

4.4 The String Type

A string is a sequence of characters.

String message = "Welcome to Java";
length()      Returns the number of characters in this string.
charAt(index) Returns the character at the specified index from this string.
concat(s1)    Returns a new string that concatenates this string with string s1.
toUpperCase() Returns a new string with all letters in uppercase.
toLowerCase() Returns a new string with all letters in lowercase
trim()        Returns a new string with whitespace characters trimmed on both sides.

4.4.3 Concatenating Strings

String s3 = s1.concat(s2);
String s3 = s1 + s2;
String myString = message + " and " + "HTML";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

4.4.4 Converting Strings

The toLowerCase() method returns a new string with all lowercase letters and the
toUpperCase() method returns a new string with all uppercase letters. For example,
“Welcome”.toLowerCase() returns a new string welcome.
“Welcome”.toUpperCase() returns a new string WELCOME.
The trim() method returns a new string by eliminating whitespace characters from both
ends of the string. The characters ’ ', \t, \f, \r, or \n are known as whitespace characters.
For example,
“\t Good Night \n”.trim() returns a new string Good Night.

4.4.5 Reading a String from the Console

Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);

The next() method reads a string that ends with a whitespace character. You can use
the nextLine() method to read an entire line of text. The nextLine() method reads a
string that ends with the Enter key pressed. For example, the following statements read a
line of text.

Scanner input = new Scanner(System.in);
System.out.println("Enter a line: ");
String s = input.nextLine();
System.out.println("The line entered is " + s);

Important Caution

To avoid input errors, do not use nextLine() after nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or next(). The reasons will be explained in Section 12.11.4, ‘How Does Scanner Work?

4.4.7 Comparing Strings

equals(s1)           Returns true if this string is equal to string s1.
equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive.
compareTo(s1)        Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive.
startsWith(prefix)   Returns true if this string starts with the specified prefix.
endsWith(suffix)     Returns true if this string ends with the specified suffix.
contains(s1)         Returns true if s1 is a substring in this string.
if (string1 == string2)
System.out.println("string1 and string2 are the same object");
else
System.out.println("string1 and string2 are different objects");
if (string1.equals(string2))
System.out.println("string1 and string2 have the same contents");
else
System.out.println("string1 and string2 are not equal");

Caution

Syntax errors will occur if you compare strings by using relational operators >, >=, <, or
<=. Instead, you have to use s1.compareTo(s2).

4.4.8 Obtaining Substrings

String message = "Welcome to Java";
String message = message.substring(0, 11) + "HTML";
The string message now becomes Welcome to HTML.
substring(beginIndex) 
Returns this string’s substring that begins with the character at the specified beginIndex and extends to the end of the string, as shown in Figure 4.2.
substring(beginIndex,endIndex)
Returns this string’s substring that begins at the specified beginIndex and extends to the character at index endIndex – 1, as shown in Figure 4.2. Note that the character at endIndex is not part of the substring

4.4.9 Finding a Character or a Substring in a String

index(ch)  Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not
matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not matched.
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not
matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched.

4.4.10 Conversion between Strings and Numbers

int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
String s = number + "";

4.6 Formatting Console Output

You can use the System.out.printf method to display formatted output on the console.

double amount = 12618.98;
double interestRate = 0.0013;
double interest = amount * interestRate;
System.out.printf("Interest is $%4.2f",interest);

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 item 1234 is 3, which is smaller than its actual size 4. The width is automatically increased to 4. The specified width for string item Java is 2, which is smaller than its actual size 4. The width is automatically increased to 4. The specified width for double item 51.6653 is 4, but it needs width 5 to display 51.67, so the width is automatically increased to 5.

Tip

The % sign denotes a format specifier. To output a literal % in the format string, use %%.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值