Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS 201 California State University, Los Angeles Various Mathematical Functions Characters Strings We have a lot of various mathematical methods in Java We’ve covered 2 so far: • Pow exponent method • Random service method There (min, max, absolute) are also many trigonometric methods • We will cover… Similar to pow, these methods are all in the Math (java)Class • Format is the same: Math.methodName Math.pow Math.sin • Note: the Math Class is in the java.lang package, and therefore doesn’t have to be imported Everything in java.lang is implicitly included in a Java program sin(r) Value of sine in radians cos(r) Value of cosine in radians tan(r) Value of tangent in radians toRadians(d) Convert degrees into radians toDegree(r) Convert radians into degrees • (Note: “degree” is singular!) asin(a) Angle (in radians) of inverse sine acos(a) Angle (in radians) of inverse cosine atan(a) Angle (in radians) of inverse tangent Keep in mind most trig method arguments are angles measured in radians Remember the range of radians: • 0 to 2π • Unit circle! The Math Class also contains two constants, PI and E • Both are doubles • Access both using Math.constantName • Math.PI 3.14159265358979323846f • Math.E 2.7182818284590452354f Simply methods that are related to exponents: • From the Math Class Math.methodName exp(n) Raises the value of e to the power n log(n) Natural Logarithm of n log10(n) Log10(n) pow(a,b) Exponent, or ab sqrt(n) The square root of n There are also methods to round • Again, from the Math Class Math.methodName ceil(x) Ceiling of x floor(x) Floor of x rint(x) x rounded up to nearest integer numbers If x is equally close to two integers, the even one is returned as a double round(x) rounds (int)Math.floor(x+0.5) for integers (long)Math.floor(x + 0.5) for doubles Note: For exactly halfway values (4.5), round(x) rounds up (5), while rint(x) rounds down (4) Contains min, max, abs, random • min(a,b) Returns the minimum of both numbers Works for int, long, float, double • max(a,b) Returns the maximum of both numbers Works for int, long, float, double • abs(x) Returns the absolute value of x Works for int, long, float, double Range review a + Math.random() * b • Returns a random number between a and a+b, excluding a+b • How do I get a random number between 15 and 20? • 400 – 4000? Compute • p123 the angles of a triangle Distance • p124 Formula We can include (and process) characters in Java! • We use the char data type • We use character literals to specify characters Type in a character between single quotes • Characters are stored in UNICODE Way to store international characters Each number is matched to a character (in a language) Was 16-bit, but that wasn’t enough space (!!!) Unicode • International Characters • Now holds up to 1,112,064 characters ASCII (American Standard Code for Information Interchange) 8-bit encoding scheme Used in most computers (Western characters) If you don’t want to input characters with string literals, you can use Unicode values • Takes 2 bytes (both in hex), preceded by \u \u03b1 \u03b2 • Note: The first 128 values in Unicode are exactly the same in ASCII, making the characters compatible Between \u0000 and \u007F You can use either ASCII or Unicode • Ex: char letter = ‘A’; char letter = ‘\u0041’; • Note: You can also use increment and decrement to get the previous or next character! char a = ‘a’; ++a; System.out.println(a); If you want to use special characters that are used by the system, computer, or Java, you must use escape sequences • Ex: (quotes, tabs, backslashes) • These represent the characters without actually writing them • Use the backslash and then a specific character to specify Backslash (\) called an escape character Different • \b • \t • \n • \f • \r • \\ • \” escape sequences backspace Tab Linefeed Formfeed Carriage return Backslash Double quote You can cast a char into a numeric type • Only the lower 16-bits of data are used You can cast a number into a char • Converted to Unicode • Floating-point values are cast to int first Numbers between 0 and FFFF in hex are implicitly casted into a char • Anything else must be explicitly casted You can compare characters using relational operators Results are generated using Unicode values • What is the result of: • ‘a’ < ‘b’ ? • ‘1’ < ‘2’ There are different methods of testing characters in the Character class • isDigit(ch) • isLetter(ch) • isLetterOrDigit(ch) • • • • a digit isLowerCase(ch) isUpperCase(ch) toLowerCase(ch) toUpperCase(ch) Returns true if ch is a digit Returns true if ch is a letter Returns true if ch is a letter or Returns true if ch is lowercase Returns true if ch is uppercase Returns the lowercase version of ch Returns the uppercase version of ch Keep in mind that char represents only one character! If you want to store multiple characters (or a string of characters) you need a String data type • Ex: String message = “Strings can store a lot more than char”; • The String data type is a reference type (not a primitive) Predefined class in Java (like System and Scanner) Any Java class can be used as a reference type for a variable The String class has its own methods. • You can access these methods by using the dot (.) operator • Methods: length() Returns the number of characters in the string charAt(index) Returns the character at the index value concat(s1) Returns a new string that concatenates the current 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 (spaces) trimmed (removed) on both sides The previous methods can only be used after a string object has been created (instantiantion) • Methods are called instance methods • Variable.methodName(arguments) The Math methods can be used without creating a Math class • These methods are called static methods • ClassName.methodName(arguments) String Length Getting Characters Concatenation Converting Case You can read in a String through console in (Scanner) • input.next(); Reads in everything to a whitespace character • nextLine() Reads in the entire line of text • Important! Do not use nextLine() after nextByte(), int, double, etc. To read in a char, use nextLine(), then use the method charAt(0); to return a character There are methods to Compare Strings: • equals(s1) Returns true if the string is equal to s1 • equalsIgnoreCase(s1) Case-insensitive version of equals • compareTo(s1) Returns an integer >0, =0, <0 if the string is >s1 • compareToIgnoreCase(s1) Case insensitive verision of compareTo equal to s1 or >s1 • StartsWith(prefix) Returns true if the string starts with the prefix • endsWith(suffix) • contains(s1) Returns true if the strings ends with the suffix Returns true if s1 is a substring Note: You may be tempted to use the comparison operator (==) in order to compare strings • DO NOT DO THIS!!!!!!! • Just checks if the strings are the same object! Do not use relational operators(<,>,=, etc) to compare strings! You may need to get substrings from your string • Substrings = Strings within strings • substring(beginIndex) Returns substring that begins with the character at the index Note: The first index is 0 • substring(beginIndex, endIndex) Returns substring the begins with the character at index, and ends at endIndex - 1 There are many different methods that find the position (index) of a character or substring within a string These methods will return -1 if unmatched indexOf(ch) Returns the index of the first occurrence of ch in the string. indexOf(ch, fromIndex) Returns the index of the first occurrence of ch in the string after fromIndex. indexOf(s) Returns the index of the first occurrence of the string s1. indexOf(s, fromIndex) Returns the index of the first occurrence of the string s1. lastindexOf(ch) Returns the index of the last occurrence of ch in the string. lastindexOf(ch, fromIndex) Returns the index of the last occurrence of ch in the string after fromIndex. lastindexOf(s) Returns the index of the last occurrence of the string s1. lastindexOf(s, fromIndex) Returns the index of the last occurrence of the string s1. You can convert a numeric string into a number • Use the Integer.parseInt() method From the Integer class Static method • Can also use Double.parseDouble() Static method You can use System.out.printf() to display formatted output on the console Within the text use different format specifiers • • • • • • %b %c %d %f %e %s boolean value character decimal (integer) floating-point number a number in scientific notation a string If you put different variables in the printf, append them after the string using commas • System.out.printf(“The Length is %d, area is %f”,length, area); You can format different precisions using System.out.printf() • P147 • Let’s do some examples! For character (c) and boolean (b) • %[width]c • %[width]b • This separates out the number of spaces displayed in the area. Value is displayed on the left Called the width • Ex: %5c Specifies 5 spaces for the character. (Adds 4 spaces, then displays the character %6b Specifies 6 spaces for the result (Adds 1 extra space for false, 2 spaces for true) For floating-point values: • %[width].[number_of_decimals]f • %[width].[number_of_decimals]e • First number specifies the minimum width • Next number specifies the number of decimals shows Note: The decimal is included in the width! • Ex: %5.2f Displays at least 5 spaces for width, and only 2 after the decimal (if there are more digits left of the decimal, they will be displayed For integers and strings: • %[width]d • %[width]s • Displays a minimum width for displaying integers or strings • If int or string is wider than minimum, it will automatically expand.