Module 4: Characters, Strings, and Mathematical Functions
|
|
- Blaise Nicholson
- 6 years ago
- Views:
Transcription
1 Module 4: Characters, Strings, and Mathematical Functions
2 Objectives To solve mathematics problems by using the methods in the Math class ( 4.2). To represent characters using the char type ( 4.3). To encode characters using ASCII and Unicode ( 4.3.1). To represent special characters using the escape sequences ( 4.4.2). To cast a numeric value to a character and cast a character to an integer ( 4.3.3). To compare and test characters using the static methods in the Character class ( 4.3.4). To introduce objects and instance methods ( 4.4). To represent strings using the String objects ( 4.4). To return the string length using the length() method ( 4.4.1). To return a character in the string using the charat(i) method ( 4.4.2). To use the + operator to concatenate strings ( 4.4.3). To read strings from the console ( 4.4.4). To read a character from the console ( 4.4.5). To compare strings using the equals method and the compareto methods ( 4.4.6). To obtain substrings ( 4.4.7). To find a character or a substring in a string using the indexof method ( 4.4.8). To program using characters and strings (GuessBirthday) ( 4.5.1). To convert a hexadecimal character to a decimal value (HexDigit2Dec) ( 4.5.2). To revise the lottery program using strings (LotteryUsingStrings) ( 4.5.3). To format output using the System.out.printf method ( 4.6). Module 4: Characters, Strings, and Mathematical Functions page 2
3 Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this module. Module 4: Characters, Strings, and Mathematical Functions page 3
4 Summary: Motivations This module introduced additional basic features of Java These features include Strings, Characters, and additional Mathematical Functions Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical functions. Module 4: Characters, Strings, and Mathematical Functions page 4
5 Common Mathematical Functions Method: A group of statements that performs a specific task You have already seen several methods: pow(a, b): to compute a b random(): generate a random number Both of these methods are inside the Math class There are many other beneficial methods inside the Math class as well Module 4: Characters, Strings, and Mathematical Functions page 5
6 Class constants: PI E The Math Class Class methods can be categorized as: Trigonometric Methods Exponent Methods Service methods You can use these constants as Math.PI and Math.E in any program. rounding, min, max, abs, and random Methods Module 4: Characters, Strings, and Mathematical Functions page 6
7 Trigonometric Methods The parameter of sin, cos, and tan is an angle in radians The return value of asin, acos, and atan is a degree in radians Module 4: Characters, Strings, and Mathematical Functions page 7
8 Trigonometric Methods Examples: Math.toDegrees(Math.PI / 2); //returns 90.0 Math.toRadians(30); Math.sin(0); //returns 0.0 //returns (same as π/6) Math.sin(Math.toRadians(270)); // returns -1.0 Math.sin(Math.PI / 6); // returns 0.5 Math.sin(Math.PI / 2); // returns 1.0 Math.cos(0); // returns 1.0 Math.cos(Math.PI / 6); // returns Math.cos(Math.PI / 2); // returns 0 Math.asin(0.5); Math.acos(0.5); Math.atan(1.0); // returns (same as π/6) //returns (same as π/3) // returns (same as π/4) Module 4: Characters, Strings, and Mathematical Functions page 8
9 Exponent Methods Module 4: Characters, Strings, and Mathematical Functions page 9
10 Exponent Methods Examples: Math.exp(1); // returns 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 Math.sqrt(4); // returns 2.0 Math.sqrt(10.5); // returns 4.24 Module 4: Characters, Strings, and Mathematical Functions page 10
11 Rounding Methods Math class contains five rounding methods: double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. int round(float x) Return (int)math.floor(x+0.5). long round(double x) Return (long)math.floor(x+0.5). Module 4: Characters, Strings, and Mathematical Functions page 11
12 Rounding Methods Examples: Math.ceil(2.1); //returns 3.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 -3.0 Math.rint(2.1); //returns 2.0 Math.rint(2.0); //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(-2.5); //returns -2.0 Math.round(2.6f); //returns 3 Math.round(2.0); //returns 2 Math.round(-2.0f); //returns -2 Math.round(-2.6); //returns -3 Module 4: Characters, Strings, and Mathematical Functions page 12
13 min and max methods min, max, and abs min(a, b): returns minimum of a and b max(a, b): returns the maximum of a and b abs method: abs(a): returns the absolute value of a Examples: Math.max(2, 3); //returns 3 Math.max(2.5, 3); //returns 3 Math.min(2.5, 4.6); //returns 2.5 Math.abs(-2); //returns 2 Math.abs(-2.1); //returns 2.1 Module 4: Characters, Strings, and Mathematical Functions page 13
14 The random Method Generates a random double value This value is greater than or equal to 0.0 and less than <= Math.random() < 1.0 Examples: (int)(math.random() * 10); returns a random integer between 0 and (int)(math.random() * 50); returns a random integer between 50 and 99 a + Math.random() * b; returns a random number between a and a+b, excluding a+b Module 4: Characters, Strings, and Mathematical Functions page 14
15 Evaluate the following method calls: a. Math.sqrt(4) b. Math.pow(2,3) c. Math.rint(-2.5) d. Math.ceil(7.1) e. Math.ceil(-2.8) f. Math.floor(-2.2) g. Math.floor(9.9) h. Math.round(2.5) i. Math.round(Math.abs(-3.5)) Module 4: Characters, Strings, and Mathematical Functions page 15
16 Character Data Type Java allows you to process characters using the character data type, char char represents a single character a character literal is enclosed in single quotation marks Examples: char letter = A ; Assigns the character A to the char variable letter char numchar = 4 ; Assigns the digit character 4 to the char variable numchar Module 4: Characters, Strings, and Mathematical Functions page 16
17 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 There are different ways to encode a character Java uses Unicode Unicode is an encoding scheme Originally designed for 16-bit character encoding This allowed for 2 16 = 65,536 characters Module 4: Characters, Strings, and Mathematical Functions page 17
18 Unicode Unicode and ASCII code So Unicode originally allowed only 65,536 characters Is that enough characters to represent all the characters in the world? The answer is no. So Unicode has been extended to allow 1,112,064 different types of characters These are called supplementary characters We will not discuss those characters in CPCS-202 For simplicity, we consider only the original 16-bit Unicode characters (stored in a char variable) Module 4: Characters, Strings, and Mathematical Functions page 18
19 Unicode Unicode and ASCII code Again, we only consider 16-bit Unicode characters Remember: one byte is eight bits So a 16-bit Unicode requires two bytes, preceded by \u Also, because reading 16 bits is cumbersome and difficult, Unicode is usually expressed in hexadecimal Remember: Decimal number system: 10 digits from 0 to 9 Hexadecimal number system: 16 digits from 0 to F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F We need 4 bits to represent a Hex digit Example: 15 in decimal is 1111 in binary and F in Hex Module 4: Characters, Strings, and Mathematical Functions page 19
20 Unicode Unicode and ASCII code Hex system: Module 4: Characters, Strings, and Mathematical Functions page 20
21 Unicode Unicode and ASCII code Unicode is usually expressed in Hexadecimal 16 bits in Unicode Each hexadecimal requires 4 bits So that means each Unicode is expressed in 4 Hex digits! From \u0000 to \uffff Example: Module 4: Characters, Strings, and Mathematical Functions page 21
22 Unicode and ASCII code ASCII Most computers use ASCII American Standard Code for International Exchange 8-bit encoding scheme Used to represent all uppercase and lowercase letters, all digits, all punctuation marks, and control characters 128 characters total Unicode includes ASCII code \u0000 to \u007f representing the 128 ASCII characters Module 4: Characters, Strings, and Mathematical Functions page 22
23 Unicode and ASCII code ASCII You can use both ASCII and Unicode in your program The following statements are equivalent: char letter = A ; char letter = \u0041 ; // A s Unicode value is 0041 Both statements assign character A to the char variable letter Module 4: Characters, Strings, and Mathematical Functions page 23
24 Escape Sequences for Special Characters What if you want to print a message with quotation marks printed in the output. Can you do this: System.out.println("He said "Java is fun""); Answer: No! This statement will give a compile error. The compiler will see the quotation before the word Java. And the compiler will assume this is the END of the string! So it gets confused when it sees more characters after How do we overcome this problem? Escape Sequences Module 4: Characters, Strings, and Mathematical Functions page 24
25 Escape Sequences for Special Characters Escape Sequences: Java uses a special notation to represent special characters This notation is called an escape sequence Example escape sequences are shown in the table below: Module 4: Characters, Strings, and Mathematical Functions page 25
26 Escape Sequences for Special Characters Escape Sequences: So we use a backslash (\) followed by a character or a combination of digits Example: System.out.println("He said \" Java is fun\""); The output is: He said "Java is fun" Note that the symbols \ and " together represent one character Module 4: Characters, Strings, and Mathematical Functions page 26
27 Escape Sequences for Special Characters Escape Sequences: So what if you wanted to actually print a backslash Example: what if you wanted to print the following: \t is a tab character So we actually want to print the backslash to the screen How can you do this? Backslash is an escape character Using a backslash signals to the compiler that a special character should be printed So how do we actually print the backslash: we escape it! System.out.println("\\t is a tab character"); Module 4: Characters, Strings, and Mathematical Functions page 27
28 Casting between char and Numeric Types Implicit casting: Implicit casting can be used if the result of casting fits into the target variable. Otherwise, explicit casting is required Example: Unicode of 'a' is 97 This is within the range of a byte (and of course an int) So the following are okay: byte b = 'a'; // same as byte b = (byte)'a'; int i = 'a'; char c = 97; // same as int i = (int)'a'; // same as char c = (char)97; Module 4: Characters, Strings, and Mathematical Functions page 28
29 Casting between char and Numeric Types Explicit casting: The following would be incorrect: byte b = '\ufff4'; Why? Because the right side is 16 bits. A byte is 8 bits Clearly, 16 bits does not fit into 8 bits To force the assignment, use explicit casting: byte b = (byte)'\ufff4'; Remember: a char uses two bytes So any positive integer between 0000 and FFFF in hexadecimal can be cast into a char implicitly. Module 4: Characters, Strings, and Mathematical Functions page 29
30 Casting between char and Numeric Types Numeric operators All numeric operators can be applied to char operands A char operand is automatically cast into a number if the other operand is a number or a character But if the other operand is a string, the character is concatenated with the string Module 4: Characters, Strings, and Mathematical Functions page 30
31 Casting between char and Numeric Types Numeric operators Examples: int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System.out.println("i is " + i); // i is 101 int j = 2 + 'a'; // (int)'a' is 97 System.out.println("j is " + j); // j is 99 System.out.println("Module " + '2'); System.out.println(j + " is the Unicode for character " + (char)j); Output: i is 101 j is 99 Module 2 99 is the Unicode for character c Module 4: Characters, Strings, and Mathematical Functions page 31
32 Comparing and Testing Characters Two characters can be compared using relational operators just like comparing two numbers This is done by comparing the Unicode values Examples: 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). 'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65). '1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8' (56). Module 4: Characters, Strings, and Mathematical Functions page 32
33 Comparing and Testing Characters Often you must test whether a character is a number, a letter, or even if it is uppercase or lowercase. The following code tests whether a character ch is an uppercase letter, a lowercase letter, or a digit: if (ch >= 'A' && ch <= 'Z') System.out.println(ch + " is an uppercase letter"); else if (ch >= 'a' && ch <= 'z') System.out.println(ch + " is a lowercase letter"); else if (ch >= '0' && ch <= '9') System.out.println(ch + " is a numeric character"); Module 4: Characters, Strings, and Mathematical Functions page 33
34 Methods in the Character Class Testing characters is common Therefore, Java gives the following methods inside the Character class Module 4: Characters, Strings, and Mathematical Functions page 34
35 Methods in the Character Class Using the Character class: Examples: System.out.println("isDigit('a') is " + Character.isDigit('a')); System.out.println("isLetter('a') is " + Character.isLetter('a')); System.out.println("isLowerCase('a') is " + Character.isLowerCase('a')); System.out.println("isUpperCase('a') is " + Character.isUpperCase('a')); System.out.println("toLowerCase('T') is " + Character.toLowerCase('T')); System.out.println("toUpperCase('q') is " + Character.toUpperCase('q')); Output: isdigit('a') is false isletter('a') is true islowercase('a') is true isuppercase('a') is false tolowercase('t') is t touppercase('q') is Q Module 4: Characters, Strings, and Mathematical Functions page 35
36 Evaluate the following : System.out.println('a' < 'b'); System.out.println('a' <= 'A'); System.out.println('a' > 'b'); System.out.println('a' >= 'A'); System.out.println('a' == 'a'); System.out.println('a'!= 'b'); true false false true true true Module 4: Characters, Strings, and Mathematical Functions page 36
37 What is the output of the following program: public class Test { public static void main(string[] args) { char x = 'a'; char y = 'c'; System.out.println(++x); System.out.println(y++); System.out.println(x - y); } } Output: b c -2 Module 4: Characters, Strings, and Mathematical Functions page 37
38 Write code that generates a random lowercase letter. Remember: lowercase letters are 97 to 122 in decimal So 26 possible values (letters) public class RandomLowercase{ public static void main(string[] args) { int x = 97 + (int)(math.random() * 26); char randomchar = x; System.out.println("Random char: " + randomchar); } } Module 4: Characters, Strings, and Mathematical Functions page 38
39 The String Type A char represents one character So how do we represent a sequence (a string) of characters? Use the data type called String Example: The following code declares variable message to be a string with the value "Welcome to Java" String message = "Welcome to Java"; Module 4: Characters, Strings, and Mathematical Functions page 39
40 String details: The String Type String is a predefined class in the Java library Just like the classes System and Scanner The String type is not a primitive type It is known as a reference type And the variable declared by a reference type is known as a reference variable that references an object String message = "Welcome to Java"; Here, message is a reference variable that references a string object with the contents "Welcome to Java" Module 4: Characters, Strings, and Mathematical Functions page 40
41 String details: The String Type Declaring a String variable: String firstname; Assign a value to the String variable: firstname = "Muhammad Alzahrani"; Most important: How to use the methods in the String class The following page shows some of the common methods that can be used to operate on Strings Module 4: Characters, Strings, and Mathematical Functions page 41
42 Simple Methods for String Objects String details: Strings are objects in Java For this reason, these methods are called "instance methods" A non-instance method is called a static method All methods in the Math class are static methods They are not tied to a specific object instance Module 4: Characters, Strings, and Mathematical Functions page 42
43 Simple Methods for String Objects String details: Again, string methods are instance methods This means that they are tied to a specific object/string Therefore, you must invoke them from a specific object/string Syntax: referencevariable.methodname(arguments) Recall: syntax to invoke a static method: ClassName.methodName(arguments) Example: Math.pow(2, 3); // result is 8 So instead of mentioning the Class of the method We mention the specific variable Module 4: Characters, Strings, and Mathematical Functions page 43
44 Simple Methods for String Objects Getting String Length Use the length() method to return the number of characters in a string Example: String message = "Welcome to Java"; System.out.println("The length of " + message + " is " + message.length()); Output: The length of Welcome to Java is 15 Module 4: Characters, Strings, and Mathematical Functions page 44
45 Simple Methods for String Objects Getting Characters from a String The s.charat(index) method can be used to retrieve a specific character in a string s The index is between 0 and s.length()-1 Example: message.charat(0); // Returns the character W Module 4: Characters, Strings, and Mathematical Functions page 45
46 Simple Methods for String Objects Concatenating Strings You can use the concat method to concatenate two strings Example: Strings s3 = s1.concat(s2); concatenates s1 and s2 into s3 String concatenation is very common in Java Therefore, Java gives is the plus (+) operator for this Example: String s3 = s1 + s2; Module 4: Characters, Strings, and Mathematical Functions page 46
47 Simple Methods for String Objects Concatenating Strings Remember: you can concatenate a number with a string At least one of the operands must be a string Examples: String message = "Welcome " + "to " + "Java"; String s = "Module " + 2; s becomes "Module 2" String s1 = "Supplement " + 'B'; s1 becomes "Supplement B" Module 4: Characters, Strings, and Mathematical Functions page 47
48 Simple Methods for String Objects Concatenating Strings The augmented += operator can also be used for concatenation with strings Example: String message = "Welcome to Java"; message += ", and Java is fun."; System.out.println(message); Output: "Welcome to Java, and Java is fun." Module 4: Characters, Strings, and Mathematical Functions page 48
49 Simple Methods for String Objects Concatenating Strings Final example: If i=1 and j=2, what is the output of the following: System.out.println("i + j is " + i + j); Output: "i + j is 12" Why? In Java, we read from left to right So we have the String "i + j is " concatenated with the int i The result: a new String ("i + j is 1") This new String is the concatenated with the int j You can force addition by enclosing the i + j in parentheses Module 4: Characters, Strings, and Mathematical Functions page 49
50 Simple Methods for String Objects Converting Strings Methods: tolowercase() method returns a new string with all lowercase letters touppercase() method returns a new string with all uppercase letters trim() method returns a new string after removing all whitespace characters from both ends of the string Final example: "Welcome".toLowerCase(); // returns a new string welcome "Welcome".toUpperCase(); // returns a new string WELCOME "\t a b c ".trim(); // returns a new string a b c Module 4: Characters, Strings, and Mathematical Functions page 50
51 Reading a String from the Console How to read a string from the console Use the next() method on a Scanner object System.out.print("Enter three words separated by spaces: "); String s1 = input.next(); // assume we made Scanner object 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); Module 4: Characters, Strings, and Mathematical Functions page 51
52 Reading a String from the Console How to read a complete line from the console Use the nextline() method on a Scanner object Scanner input = new Scanner(System.in); System.out.println("Enter a line: "); String s = input.nextline(); System.out.println("The line entered is " + s); Module 4: Characters, Strings, and Mathematical Functions page 52
53 Reading a Character from the Console How to read a single character from the console Use the nextline() method to read a string and then invoke the charat(0) method on the string Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); String s = input.nextline(); char ch = s.charat(0); System.out.println("The character entered is " + ch); Module 4: Characters, Strings, and Mathematical Functions page 53
54 Comparing Strings The String class has many methods you can use to compare two strings. Module 4: Characters, Strings, and Mathematical Functions page 54
55 String equality Comparing Strings How can you check if two strings are equal? Note: you cannot use the == operator Example: if (s1 == s2) else System.out.println("s1 and s2 are the same object"); System.out.println("s1 and s2 are different object"); This will only tell us if two string reference variables point to (refer to) the same object Module 4: Characters, Strings, and Mathematical Functions page 55
56 String equality Comparing Strings So how can you check if two strings are equal? Meaning, how to check if they have same contents? Use the equals() method Example: if (s1.equals(s2)) else System.out.println("s1 and s2 have same contents"); System.out.println("s1 and s2 are not equal"); Module 4: Characters, Strings, and Mathematical Functions page 56
57 String equality Comparing Strings Example: String s1 = "Welcome to Java"; String s2 = "Welcome to Java"; String s3 = "Welcome to C++"; System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false Module 4: Characters, Strings, and Mathematical Functions page 57
58 Comparing Strings compareto() method We can use the compareto() method to compare two strings This allows us to alphabetically order the strings Syntax: s1.compareto(s2); Returns the value 0 if s1 is equal to s2 Returns a value less than 0 if s1 is "less than" s2 Returns a value greater than 0 if s1 is "greater than" s2 Example: "abc".compareto("abg"); // returns -4 Module 4: Characters, Strings, and Mathematical Functions page 58
59 Program 1: OrderTwoCities Write a program that prompts the user to enter two cities and then displays them in alphabetical order. Remember: Step 1: Problem-solving Phase Step 2: Implementation Phase Module 4: Characters, Strings, and Mathematical Functions page 59
60 Program 1: OrderTwoCities Step 1: Problem-solving Phase Algorithm: 1. Prompt the user to enter an two Strings 2. Compare the two strings using compareto() method 3. Print the cities in correct alphabetical order Module 4: Characters, Strings, and Mathematical Functions page 60
61 Program 1: OrderTwoCities Step 2: Implementation Module 4: Characters, Strings, and Mathematical Functions page 61
62 Program 1: OrderTwoCities Run the Program: Note: Some city names have multiple words Such as New York Therefore, we used nextline() to scan the city name Instead of next() Click here to view and trace code Module 4: Characters, Strings, and Mathematical Functions page 62
63 Obtaining Substrings You can get a substring, from a string, by using the substring method in the String class Example: String message = "Welcome to Java"; String message = message.substring(0, 11) + "HTML"; System.out.println(message); Output: Welcome to HTML Module 4: Characters, Strings, and Mathematical Functions page 63
64 Obtaining Substrings Java gives you two substring methods: substring(beginindex) Returns this string's substring that begins with the character at the specified beginindex and extends to the end of the string substring(beginindex, endindex) Returns this string's substring that begins with the character at the specified beginindex and extends to the character at index endindex 1 NOTE: the character at endindex is NOT part of the substring Module 4: Characters, Strings, and Mathematical Functions page 64
65 Finding a Character or a Substring in a String The String class provides several versions of indexof and lastindexof methods to find a character or a substring in a string Module 4: Characters, Strings, and Mathematical Functions page 65
66 Finding a Character or a Substring in a String The String class provides several versions of indexof and lastindexof methods to find a character or a substring in a string Examples: "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('o') returns 4. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. Module 4: Characters, Strings, and Mathematical Functions page 66
67 Finding a Character or a Substring in a String The String class provides several versions of indexof and lastindexof methods to find a character or a substring in a string Examples: "Welcome to Java".lastIndexOf('W') returns 0. "Welcome to Java".lastIndexOf('o') returns 9. "Welcome to Java".lastIndexOf('o', 5) returns 4. "Welcome to Java".lastIndexOf("come") returns 3. "Welcome to Java".lastIndexOf("Java", 5) returns -1. "Welcome to Java".lastIndexOf("Java") returns 11. Module 4: Characters, Strings, and Mathematical Functions page 67
68 Finding a Character or a Substring in a String Practical Example Suppose a string s contains the first name and last name of a student, separated by a space How can you extract the first name and last name? Can we use a method to find the space? YES! We can use the indexof(' ') This will give us the index of the first space Then, because we know this index, we can use the substring() method to find the first name and the last name Module 4: Characters, Strings, and Mathematical Functions page 68
69 Finding a Character or a Substring in a String Practical Example Solution: String s = "Kim Jones"; int k = s.indexof(' '); String firstname = s.substring(0, k); String lastname = s.substring(k + 1); Module 4: Characters, Strings, and Mathematical Functions page 69
70 Conversion between Strings and Numbers You can convert a numeric string into an int How? Use the Integer.parseInt() method Example: int value = Integer.parseInt("152"); You can also convert a string to a double Use the Double.parseDouble() method Example: double value = Double.parseDouble("827.55"); Module 4: Characters, Strings, and Mathematical Functions page 70
71 Conversion between Strings and Numbers Can you convert a number to a String? Yes. You can do it a complicated way We won't bother showing you! OR, you do it the EASY way: int number = 7; String s = number + ""; kinda like a "hack" But it works great! We concatenate a number with the empty string Result: we get a string representation of the number! Module 4: Characters, Strings, and Mathematical Functions page 71
72 Suppose that s1, s2, and s3 are three strings: String s1 = "Welcome to Java"; String s2 = "Programming is fun"; String s3 = "Welcome to Java"; What are the results of the following expressions? a. s1 == s2 b. s1 == s3 c. s1.equals(s2) d. s1.equals(s3) e. s1.compareto(s2) f. s2.compareto(s3) g. s2.compareto(s2) h. s1.charat(0) false false false true Greater than 0 Less than 0 0 (cause contents are equal) W Module 4: Characters, Strings, and Mathematical Functions page 72
73 Suppose that s1, s2, and s3 are three strings: String s1 = "Welcome to Java"; String s2 = "Programming is fun"; String s3 = "Welcome to Java"; What are the results of the following expressions? a. s1.indexof('j') b. s1.indexof('j') c. s1.indexof("to") d. s1.lastindexof('a') e. s1.length() f. s1.substring(5) g. s1.substring(5,12) h. s1.endswith("java") 11-1 (meaning, not found) 8 (the starting index of "to") me to Java me to J true Module 4: Characters, Strings, and Mathematical Functions page 73
74 Show the output of the following expressions: a) System.out.println("1" + 1); 11 b) System.out.println('1' + 1); 50 c) System.out.println("1" ); 111 d) System.out.println("1" + (1 + 1)); 12 e) System.out.println('1' ); 51 Module 4: Characters, Strings, and Mathematical Functions page 74
75 Program 2: HexDigit2Dec Write a program that prompts the user to enter one hex digit and then displays this as a decimal value. Remember: Step 1: Problem-solving Phase Step 2: Implementation Phase Module 4: Characters, Strings, and Mathematical Functions page 75
76 Program 2: HexDigit2Dec Step 1: Problem-solving Phase Algorithm: 1. Prompt the user to enter a hex digit 2. Check to see if the input is exactly one digit 3. If so, confirm the input is between 0-9 or A-F Then print the decimal equivalent 4. Otherwise, print invalid input For step 3 above, we can use methods we've learned in this Module Module 4: Characters, Strings, and Mathematical Functions page 76
77 Program 2: HexDigit2Dec Step 2: Implementation Module 4: Characters, Strings, and Mathematical Functions page 77
78 Program 2: HexDigit2Dec Step 2: Implementation is A-F? is 0-9? Module 4: Characters, Strings, and Mathematical Functions page 78
79 Program 2: HexDigit2Dec Run the Program: Click here to view and trace code Module 4: Characters, Strings, and Mathematical Functions page 79
80 Program 3: Lottery Re-do the Lottery program from Module 3. This time, use strings for both the randomly generated number and the user input. The logic is easier than dealing with mod! Remember: Step 1: Problem-solving Phase Step 2: Implementation Phase Module 4: Characters, Strings, and Mathematical Functions page 80
81 Program 3: Lottery Step 1: Problem-solving Phase Notes: The user will win money according to the following rules: 1. If the user lottery number matches the winning lottery number in the exact order, the award is $10, If all digits in the user lottery number match all digits in the winning lottery number (but not in the exact order), the award is $3, If only one digit in the user lottery number matches the winning lottery number, the award is $1,000 User MUST enter two digits Module 4: Characters, Strings, and Mathematical Functions page 81
82 Program 3: Lottery Step 1: Problem-solving Phase Algorithm: 1. Randomly generate a winning lottery number Between 0 and 99. This is easy. int lottery = (int)(math.random() * 100); 2. Save that number as a String! 3. Prompt user for input 4. Scan the lottery number from user as a String! 5. Compare user number with winning number, and determine winning amount (if any) Here we must compare the actual digits!!! 6. Display results to user Module 4: Characters, Strings, and Mathematical Functions page 82
83 Program 3: Lottery Step 1: Problem-solving Phase So how do we compare digits? We are saving these two-digit numbers as strings Therefore, we can extract the individual digits using the String method charat() This is MUCH easier than mod! Example: String number = "49"; char c1 = number.charat(0); char c2 = number.charat(1); Module 4: Characters, Strings, and Mathematical Functions page 83
84 Program 3: Lottery Step 2: Implementation Module 4: Characters, Strings, and Mathematical Functions page 84
85 Program 3: Lottery Step 2: Implementation Module 4: Characters, Strings, and Mathematical Functions page 85
86 Run the Program: Program 3: Lottery Click here to view and trace code Module 4: Characters, Strings, and Mathematical Functions page 86
87 Formatting Output You can use the System.out.printf method to display formatted output When printing double values, often we do not need or want all the decimals. In fact, often we want only two (for money)! In Module 2, we learned that you can get two digits after the decimal as follows: double x = ; x = (int)(x * 100) / 100.0; However, if we print x, we will get 16.4 The final zero will not print! So how do we print the zero? Module 4: Characters, Strings, and Mathematical Functions page 87
88 Formatting Output You can use the System.out.printf method to display formatted output How to print with only two decimals? Easy! double x = ; System.out.printf("x is %4.2f", x); Output: x is Module 4: Characters, Strings, and Mathematical Functions page 88
89 Formatting Output You can use the System.out.printf method to display formatted output Another example: Module 4: Characters, Strings, and Mathematical Functions page 89
90 Formatting Output You can use the System.out.printf method to display formatted output Common format specifiers: Module 4: Characters, Strings, and Mathematical Functions page 90
Chapter 4 Mathematical Functions, Characters, and Strings
Chapter 4 Mathematical Functions, Characters, and Strings Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose you need to estimate
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical
More informationMathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University
Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void
More informationMathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University
Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void
More informationChapter 4 Mathematical Functions, Characters, and Strings
Chapter 4 Mathematical Functions, Characters, and Strings 4.1 Introduction The focus of this chapter is to introduce mathematical functions, characters, string objects, and use them to develop programs.
More informationCS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)
CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs How to generate
More informationComputer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #4
More informationCS-201 Introduction to Programming with Java
CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture V: Mathematical Functions, Characters, and Strings Introduction How would you estimate
More informationCS110: PROGRAMMING LANGUAGE I
CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters
More informationChapter 4. Mathematical Functions, Characters, and Strings
Chapter 4 Mathematical Functions, Characters, and Strings 1 Outline 1. Java Class Library 2. Class Math 3. Character Data Type 4. Class String 5. printf Statement 2 1. Java Class Library A class library
More information12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
12. Numbers Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Numeric Type Conversions Math Class References Numeric Type Conversions Numeric Data Types (Review) Numeric Type Conversions Consider
More informationCHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS
CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH INTRODUCTION TO JAVA PROGRAMMING, LIANG (PEARSON 2014) MATHEMATICAL FUNCTIONS Java
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationTo define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,
1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading
More informationEng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 4 Characters
More informationChapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk
Chapter 5 Methods Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Introducing Methods A method is a collection of statements that
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationComputer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #5
More informationChapter 5 Methods / Functions
Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a
More informationChapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }
Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,
More informationChapter 6 Methods. Dr. Hikmat Jaber
Chapter 6 Methods Dr. Hikmat Jaber 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationChapter 2 ELEMENTARY PROGRAMMING
Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple
More informationCOP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of
More informationChapter 12 Strings and Characters. Dr. Hikmat Jaber
Chapter 12 Strings and Characters Dr. Hikmat Jaber 1 The String Class Constructing a String: String message = "Welcome to Java ; String message = new String("Welcome to Java ); String s = new String();
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical
More informationChapter 2 Primitive Data Types and Operations
Chapter 2 Primitive Data Types and Operations 2.1 Introduction You will be introduced to Java primitive data types and related subjects, such as variables constants, data types, operators, and expressions.
More informationCalculations, Formatting and Conversions
Chapter 5 Calculations, Formatting and Conversions What is in This Chapter? In this chapter we discuss how to do basic math calculations as well as use some readily available Math functions in JAVA. We
More informationMATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U
C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS P1 LESSON 4 P1 LESSON 4.1 INTRODUCTION P1 LESSON 4.2 COMMON MATH FUNCTIONS Java
More informationUsing Java Classes Fall 2018 Margaret Reid-Miller
Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class
More information1.1 Your First Program
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 5/20/2013 9:37:22 AM Why Programming? Why programming? Need
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationBasic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection
More informationAP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education
AP Computer Science Return values, Math, and double Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode?
More informationChapter 2 Primitive Data Types and Operations. Objectives
Chapter 2 Primitive Data Types and Operations Prerequisites for Part I Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs,
More informationLecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value
Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationJAVA Programming Concepts
JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa Find the sum of integers from 1 to 10,
More information! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.
Why Java? Lecture 2: Intro to Java Java features.! Widely available.! Widely used.! Variety of automatic checks for mistakes in programs.! Embraces full set of modern abstractions. Caveat.! No perfect
More informationICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper
1 of 10 05-11-015 16:1 ICSE J Java for Class X Computer Applications ICSE Class 10 Computer Applications ( Java ) 014 Solved Question Paper ICSE Question Paper 014 (Solved) Computer Applications Class
More informationChapter 2 Primitive Data Types and Operations
Chapter 2 Primitive Data Types and Operations 2.1 Introduction You will be introduced to Java primitive data types and related subjects, such as variables constants, data types, operators, and expressions.
More information1.1 Your First Program
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 1/29/11 6:37 AM! Why Programming? Why programming? Need to
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationEntry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process
Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will
More informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
More informationLecture #6-7 Methods
Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a.
More informationVisual C# Instructor s Manual Table of Contents
Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms
More informationStrings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types
More informationChapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationThe Math Class. Using various math class methods. Formatting the values.
The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class,
More informationReview for Test 1 (Chapter 1-5)
Review for Test 1 (Chapter 1-5) 1. Introduction to Computers, Programs, and Java a) What is a computer? b) What is a computer program? c) A bit is a binary digit 0 or 1. A byte is a sequence of 8 bits.
More informationChapter 4. Mathematical Functions, Characters, and Strings. Program Listings
Chapter 4 Mathematical Functions, Characters, and Strings Program Listings Contents Listing 4.1 Compute Angles... 3 Listing 4.2 Order Two Cities... 5 Listing 4.3 Guess Birthday... 6 Listing 4.4 Hex Digit
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationVarious useful classes
Various useful classes String manipulation Mathematical functions Standard input / output File input / output Various system features Hashtable Useful graphical classes String manipulation a string is
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More information1.1 Your First Program! Naive ideal. Natural language instructions.
Why Programming? Why programming? Need to tell computer what you want it to do. 1.1 Your First Program Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies, subject
More informationLecture 2: Intro to Java
Why Java? Lecture 2: Intro to Java Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. 2 Why Java? Why Java? Java
More information1.1 Your First Program
1.1 Your First Program 1 Why Programming? Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies,
More information1.1 Your First Program
Why Programming? 1.1 Your First Program Why programming? Need to tell computer what to do. Please simulate the motion of N heavenly bodies, subject to Newton s laws of motion and gravity. Prepackaged software
More information1.1 Your First Program
Why Programming? Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." 1.1 Your First Program Prepackaged software solutions.
More informationString is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents
String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents character strings. All string literals in Java programs,
More informationAP Computer Science A. Return values
AP Computer Science A Return values Distance between points Write a method that given x and y coordinates for two points prints the distance between them Pseudocode? Java's Math class Method name Math.abs(value)
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationfalse, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4
1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45
More informationDATA TYPES AND EXPRESSIONS
DATA TYPES AND EXPRESSIONS Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical
More informationCS 1301 Ch 8, Part A
CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String
More information1.1 Your First Program
Why Programming? 1.1 Your First Program Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies, subject
More informationEntry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes
Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the
More informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationChapter 2 Part 2 Edited by JJ Shepherd, James O Reilly
Basic Computation Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly Parentheses and Precedence Parentheses can communicate the order in which arithmetic operations are performed examples: (cost +
More informationChapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 4 Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff errors
More informationCS115 Principles of Computer Science
CS115 Principles of Computer Science Chapter 5 Methods Prof. Joe X. Zhou Department of Computer Science CS115 Methods.1 Re: Objectives in Loops Sequence and selection aside, we need repetition (loops)
More informationwhen you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally
I. Methods week 4 a method consists of a sequence of instructions that can access the internal data of an object (strict method) or to perform a task with input from arguments (static method) when you
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationPrimitive Data Types: Intro
Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More information2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals
Chapter Four: Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff
More informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationMODULE 02: BASIC COMPUTATION IN JAVA
MODULE 02: BASIC COMPUTATION IN JAVA Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment
More informationBasic Computation. Chapter 2
Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers
More informationMore on variables and methods
More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class
More informationLecture 2: Intro to Java
Why Programming? Lecture 2: Intro to Java Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." Prepackaged software solutions.
More informationBasic Computation. Chapter 2
Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them
More informationAdvanced Object Concepts
Understanding Blocks Blocks - Appears within any class or method, the code between a pair of curly braces Outside block- The first block, begins immediately after the method declaration and ends at the
More informationLesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL
Lesson 02 Data Types and Statements MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Data Types Arithmetic
More informationLesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL
Lesson 02 Data Types and Statements MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Constants Data Types
More informationwww.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some
More informationLecture 6: While Loops and the Math Class
Lecture 6: While Loops and the Math Class Building Java Programs: A Back to Basic Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. while loops 2 Categories of loops
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us From this site you can click on the COSC-236
More informationWelcome to the Using Objects lab!
Welcome to the Using Objects lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 3 terms. 2. Describe reference variables and compare with primitive data type variables. 3. Draw
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More information1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 41 / 68 Example Given the radius
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems
More informationCS1150 Principles of Computer Science Math Functions, Characters and Strings
CS1150 Principles f Cmputer Science Math Functins, Characters and Strings Yanyan Zhuang Department f Cmputer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Clrad Springs Mathematical Functins Java
More information