Presentation is loading. Please wait.

Presentation is loading. Please wait.

String, Math and the char Type

Similar presentations


Presentation on theme: "String, Math and the char Type"— Presentation transcript:

1 String, Math and the char Type
Here we focus on the Math class, the String class, and the char type The Math class is not like Scanner or Random because it does not need to be imported it is also not like Scanner, Random or String because we do not create a variable of type Math, instantiate it and pass messages to that variable instead we pass messages directly to the Math class itself Math.message(params); We have already seen 4 messages: abs, pow, random, sqrt, others include exp(x) – return the value of ex (e is a mathematical constant) log(x) – return the value of log e x (this is known as the natural log) log10(x) – return the value of log 10 x sin(x), cos(x), tan(x) – x is in radians and returns an angle asin(x), acos(x), atan(x) – x is an angle and returns a value in radians toRadians(x) – returns angle x in radians toDegree(x) – returns radian x in degrees All of these methods return double values but can accept int or double (or float) params

2 More Math Methods For rounding values
ceil(x) – x is rounded up to the next integer but returned as a double floor(x) – x is rounded down to the nearest integer but returned as a double rint(x) – x is rounded up to the nearest integer and returned as a double, but if the number is exactly halfway (.5), it returns the value that is even (e.g., rint(5.5) returns 6.0 and rint(6.5) returns 6.0) round(x) – adds .5 to x and then truncates the value, returning an int (or a long if x is a double) Minimum and maximum are min(x, y) and max(x, y) these return whatever type is wider between x and y if x is an int and y is a double, it returns a double Absolute value is abs(x) and it returns whatever type x is Math.abs(-5) is 5 while Math.abs(-5.1) is 5.1 Math has defined constants for E and PI denoted as Math.E and Math.PI

3 The char Type The char type stores a single character placed in ‘ ’ when specified as a literal Java supports both ASCII and Unicode characters ‘a’ and ‘A’ are different characters Unicode values are stored in at least 2 bytes but may be longer (Unicode now incorporates over 1 million characters) by default, all characters on the keyboard are stored in ASCII to store a character not on the keyboard, you must indicate its Unicode number as a hexadecimal value (0-9, A-F as in 03b1 which is the Greek alpha letter) To indicate that a set of hexadecimal digits should be encoded in Unicode, precede the value with \u as in char x = ‘\u03b1’; the \ is the escape character which is used to “treat a character by special meaning” Other useful escape characters are ‘\n’ is a carriage return ‘\t’ is a tab ‘\\’ represent a backslash See more on page 126

4 Operations on chars We can compare chars using <, >, <=, >=, ==, != for instance (x >= ‘a’ && x <= ‘z’) We can add to and subtract from chars for instance, char x = ‘a’; x++; // x now stores ‘b’ Cast between int and char types if we have a value stored in an int, casting it to a char means that we are taking that number and exchanging it with the ASCII value at that position in the ASCII table for instance: int i = 97; char c = (char)i; // c is now ‘a’ or: char c = ‘a’; int x = (int)c – 10; // x is 87 consider int y = ‘1’ + ‘2’; // ‘1’ is 49, ‘2’ is 50, y = 99 If we add to a char (e.g., c + 1), the value is coerced into an int, we need to cast it back to a char if we want it to be treated as a char: char c = ‘a’; c = (char)(c + 1); // c + 1 is 98, (char)c is ‘b’

5 The Character Class Do not confuse char and Character
char is a primitive type Character is a class whose objects store single char values Why do we need Character? We don’t usually But Character has some useful built-in methods that we might want to apply to a char isDigit(ch) – true if ch is a digit (‘0’, ‘1’, … ‘9’) isLetter(ch) – true if ch is a letter (upper or lower case) isLetterOrDigit(ch) – true if ch is a letter or a digit isLowerCase(ch), isUpperCase(ch) – case of ch must match toLowerCase(ch), toUpperCase(ch) – returns the version of ch with the new case if ch is a letter, otherwise it returns ch unchanged We reference the above methods like we would Math by passing them directly to the Character class as in Character.isDigit(ch)

6 The String Class The String class, like Math and Char, is built-in so we don’t import it But we do have to declare variables of type String and use them String gives us a shortcut on instantiation though, we can use new but we don’t have to String someString = new String(“some value”); or String someString = “some value”; As Strings are objects, we pass them messages we do not treat them like the primitive types so instead of <, >, ==, etc, we use compareTo and equals/equalsIgnoreCase the only arithmetic operator available for Strings is + to perform String concatenation as in str3 = str1 + str2; We can store the “empty string” in a String (we might do this to initialize a String) String someString = “”;

7 String Methods str1.equals(str2), str1.equalsIgnoreCase(str2), str1.compareTo(str2) – as we covered in chapter 3 str1.length( ) – returns the number of characters stored in str1 str1.concat(str2) – concatenation, same as str1 + str2 str1.charAt(i) – returns the character at index i of str1 the first character is at index 0 if str1 = “hello” then str1.charAt(0) is ‘h’, str1.charAt(1) is ‘e’, etc str1.toUpperCase( )/str1.toLowerCase( ) returns str1 where all letters are changed to the case specified, non-letters are unchanged str1.replace(char1, char2) – returns a version of str1 where every instance of character char1 is replaced by char2 str1.trim( ) – return a version of str1 with white space removed note: Strings are immutable, these methods do not change str1, merely return a new String which is a copy of str1 except with the specified change(s)

8 Example public class StringExample {
public static void main(String[] args) { String str1 = “hello there!”; String str2, str3; str2 = str1.toUpperCase( ); System.out.println(str1 + “ ” + str2); str2 = str1.replace(‘E’, ‘3’); str3 = str2.concat(str1); System.out.println(str3); System.out.println(str1.charAt(0) + “ ” + str2.charAt(0)); System.out.println(str1.trim()); System.out.println(str1); } Output: hello there HELLO THERE hello there H3LLO TH3R3 H3LLO TH3R3hello there h H hellothere hello there

9 Other String Methods str1.startsWith(str2)/str1.endsWith(str2)/str1.contains(str2) returns true if str1 starts/ends with the substring str2 or contains str1 characters of str2 must be found consecutively in str1 to match str1.substring(i) returns the portion of str1 starting at index i until the end of the str1 str1.substring(i, j) returns the portion str1 starting at index i up to but not including index j if str1 = “abcdefg” then str1.substring(3, 6) returns “def” str1.index(ch)/str1.index(s) returns the index of the first occurrence of the character ch or String s in str1 str1.indexOf(ch, i)/str1.indexOf(s, i) returns the index of the first occurrence of the character ch or String s in str1 starting at index i there are also lastIndexOf(ch), lastIndexOf(s), lastIndexOf(ch, i), lastIndexOf(s, i) where it searches backward from the end of the String until it finds ch or s remember: the first character of a String is at index 0, not 1!

10 Converting Strings and Other Types
To obtain a single character of a string use str1.charAt(i) for instance, to input a char instead of a String use in.next().charAt(0); If a String is storing a numeric value (for instance “12345” or “1.2345”) you can obtain the numeric version of it as an int, float or double Integer.parseInt(str1) Float.parseFloat(str1) Double.parseDouble(str1) if the String is not storing the type being parsed for, you get a run-time Exception To convert a number to a String, use the following notation, assume x is a numeric type (int or double) String y = “” + x; // “” is the empty String, + concatenates x onto it Integer, Double and Float classes are automatically loaded like Math, Character and String so no importing is needed

11 Formatted Output Recall earlier outputting values stored in double variables may give us more decimal points of accuracy than desired We can use System.out.printf to format our output printf formatting is similar to C/C++’s printf Syntax: System.out.printf(“specification string”, var, var, var, …); the specification string includes any literal output along with format specifiers for every variable a format specifier is %d.dc where d.d specifies the size and c specifies the type of datum use %dc for int and String where d is the minimum width use %d.dc for floating point values where the first d is the minimum width of the output of the floating point value and the second d is the number of decimal points of precision minimum width will cause the output to be padded with blank spaces on the left the d’s can be omitted add a hyphen(-) after % if you want the variable to be left justified

12 Specifier Information
The following letters are used to indicate the type to output %b (boolean) %c (char) %d (decimal integer) %f (floating point number – double or float) %e (floating point number in scientific notation) %s (String) When using .d for floating point, remember that the decimal point counts as a character When using d, if your value is too small for the output, the d is ignored (for instance, “%5d” and the variable is a 7-digit number, all 7 digits are output Examples %15s – a String of 15 characters (add blanks to the left to fill out the 15 spaces as needed) %6d – an int value to 6 total spaces (add blanks as needed) %5.2f – a floating point value with 2 decimal points of accuracy and 5 total characters including the decimal point %2c – output the character but add a blank space before the character

13 Example public class FormattingDemo {
public static void main(String[] args) { int degrees = 30; double radians = Math.toRadians(degrees); System.out.printf("%-10s%-10s%-10s%-10s%-10s\n", "Degrees", "Radians", "Sine", "Cosine", "Tangent"); 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); } Degrees Radians Sine Cosine Tangent


Download ppt "String, Math and the char Type"

Similar presentations


Ads by Google