Вы находитесь на странице: 1из 10

Mathematical Functions,

Characters, and Strings Mathematical Functions


in Java
CSE 114: Computer Science I
Stony Brook University

Math in Java Trigonometric Methods


■ Java’s Math class provides a large number of useful
Method Description
mathematical methods and constants
sin(radians) Returns the sine of an angle in radians
■ These methods include trigonometric methods, exponent cos(radians) Returns the cosine of an angle in radians
methods, and service methods tan(radians) Returns the tangent of an angle in radians

■ Today, we will briefly cover some of these methods toRadians(degrees) Converts an angle in degrees into radians
toDegrees(radians) Converts an angle in radians into degrees
■ Each method name is preceded by Math. asin(a) Returns inverse sine in radians

■ Reference: Liang, Chapter 4 (and sections 2.9.4 and 3.7) acos(a) Returns inverse cosine in radians
atan(a) Returns inverse tangent in radians
Exponent Methods Service Methods
Method Description Method Description
ceil(x) Rounds x up to its nearest integer
exp(x) Returns e to the power of x (ex)
floor(x) Rounds x down to its nearest integer
log(x) Returns the natural logarithm of x rint(x) Rounds x to its nearest integer.*

log10(x) Returns the base 10 logarithm of x round(x) Rounds x to the nearest integer
min(a, b) Returns the smaller of two values
pow(a, b) Returns a raised to the power of b (ab)
max(a, b) Returns the larger of two values
sqrt(x) Returns square root of x for x >= 0 abs(n) Returns the absolute value of n

Generating Random Numbers Mathematical Constants


■ Math.random() generates a random double value ■ The Math class also defines two common mathematical
greater than or equal to 0.0 and less than 1.0. constants:
■ Math.PI

■ Multiply this value by an integer n to generate a random ■ Math.E


value in the range 0–n:


// Generate an int between 0 and 9

int v = (int)(Math.random() * 10);
Programming Problem
■ The side of a pentagon can be computed by


s = 2 * r * sin(p/5)
 Characters in Java

where r is the length from the center of a pentagon to a
vertex
■ The area of a pentagon can be computed by


area = (5 * s * s) / (4 * tan(p/5))

Character Data Type Unicode Format


Four hexadecimal digits. Java characters use Unicode, a 16-bit encoding scheme
char letter = 'A'; (ASCII) established by the Unicode Consortium to support the
char numChar = '4'; (ASCII) interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes, preceded
char letter = '\u0041'; (Unicode) by \u, expressed in four hexadecimal numbers that run from
char numChar = '\u0034'; (Unicode) '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1
characters.
NOTE: The increment and decrement operators can also be used
Unicode \u03b1 \u03b2 \u03b3 for three Greek
on char variables to get the next or preceding Unicode character. letters
For example, the following statements display character b.
char ch = 'a';
System.out.println(++ch);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 11 reserved. 12
ASCII Code for Commonly Used Characters Escape Sequences for Special Characters

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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 13 reserved. 14

Appendix B: ASCII Character Set ASCII Character Set, cont.


ASCII Character Set is a subset of the Unicode from \u0000 to \u007f ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 15 reserved. 16
Casting between char and Comparing and Testing
Numeric Types Characters
int i = 'a'; // Same as int i = (int)'a'; if (ch >= 'A' && ch <= 'Z')
System.out.println(ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
char c = 97; // Same as char c = (char)97; System.out.println(ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
System.out.println(ch + " is a numeric character");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 17 reserved. 18

Methods in the Character Class

Method Description

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)
isUpperCase(ch)
Returns true if the specified character is a lowercase letter.
Returns true if the specified character is an uppercase letter. Strings in Java
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 19
A string is just a sequence of characters
Strings can have 0 or more characters
String Methods
(an empty string is still a sequence)
The String class is probably the most String() — creates a new String
frequently used class in Java programming String s = new String(“Hello!”);
It’s automatically provided to all Java Shorthand: String s = “Hello!”;
programs (it lives in the java.lang
package) This shorthand only works for String!
Let’s take a quick look at the methods length() — returns the total number of
provided by the String class... characters in the String

21 22

Extracting Data
String Adjustments From Strings
trim() — returns a new String
with no leading or trailing whitespace The positions in a String are
numbered from 0 to (length - 1)
toLowerCase()/toUpperCase()
— return a new copy of the String in charAt() — returns the character at
lower/uppercase a given position (index)

All three methods leave the original indexOf(str) — returns the first
String unchanged index at which str occurs in the string
(or -1 if it isn’t there)
Java strings are immutable

23 24
Extracting Data Finding a Character or a Substring in a
String
From Strings, cont’d
Method Description
substring(start, end) — returns a indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
new String containing the characters indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
from position start up to (but not Returns -1 if not matched.

including) end 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
You can also call substring() with fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not
exactly one argument matched.
lastIndexOf(ch, Returns the index of the last occurrence of ch before fromIndex in this
In this case, it returns everything from fromIndex) string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
the specified index through the end lastIndexOf(s, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.

25 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 26

Finding a Character or a Substring in a


String
String Equality
int k = s.indexOf(' '); What makes two Strings equal?
String firstName = s.substring(0, k);
Do they have the same length? The
String lastName = s.substring(k + 1); same case? The same characters?
According to Java, 


“abcdef ” == “abcdef ”


is false (they are not the same).
What gives?

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 27
28
Objects & Primitives Java is Shallow
Java performs shallow comparisons by
default (using the == operator)
Remember the difference between primitive
(built-in) types and objects A shallow comparison looks at the value
immediately associated with a variable
Primitive variables hold an actual value
This is okay for primitive types
Object variables (references) only hold the
address of an object! For objects, this means that we compare
their memory addresses, not their contents!
This causes problems when we try to
compare two objects Objects are only “equal” if they live at the
same memory address

29 30

String Equality Comparing Strings


String has methods to test equality compareTo() — compares two strings
based on content, not memory location for their relative lexicographical ordering
equals() — returns true if two case, then alphabetical, then by length
Strings have the same sequence of Usage: firstString.compareTo(secondString)
characters
This method returns an integer value
Usage: firstString.equals(secondString)
Result Positive 0 Negative
equals() requires both strings to have Meaning first > second first == second first < second
identical capitalization

31 32
Don’t Be So Two More
Sensitive! Comparisons
Problem: equals() and
compareTo() are case-sensitive
Sometimes, we only want to compare Use these methods to test the
two Strings by length and/or beginning or end of a String value:
characters startsWith(x)
Java has two more methods for this endsWith(x)
situation:
equalsIgnoreCase()

33 34

Conversion between Strings and Formatting Output

Numbers Use the printf statement.


System.out.printf(format, items);
int intValue = Integer.parseInt(intString); Where format is a string that may consist of substrings and
double doubleValue = Double.parseDouble(doubleString); format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
String s = number + ""; character, boolean value, or a string. Each specifier begins with
a percent sign.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 35 reserved. 36
Frequently-Used Specifiers

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"

int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights
reserved. 37

Вам также может понравиться