Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227
1... 2 int[] hist = new int[5]; 3 // hist[0]: the counter for 90 100 4 // hist[1]: the counter for 80 89 5 //... 6 // hist[4]: the counter for 0 59 7 8 Scanner in = new Scanner(System.in); 9 int inputvalue; 10 do { 11 do { 12 System.out.println("Enter x? ( 1 to exit)"); 13 inputvalue = in.nextint(); 14 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 15 if (inputvalue >= 90) ++hist[0]; 16 else if (inputvalue >= 80) ++hist[1]; 17 else if (inputvalue >= 70) ++hist[2]; 18 else if (inputvalue >= 60) ++hist[3]; 19 else if (inputvalue >= 0) ++hist[4]; 20 else System.out.println("End of input."); 21 } while (inputvalue!= 1); 22 in.close(); 23 Zheng-Liang Lu Java Programming 198 / 227
24 int total = 0; 25 for (int i = 0; i < hist.length; i++) { 26 total += hist[i]; 27 } 28 System.out.printf("Total: %d\n", total); 29 30 int[] tick = {0, 60, 70, 80, 90, 101}; 31 for (int i = 0; i < 5; i++) { 32 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 33 for (int j = 0; j < hist[i]; j++) { 34 System.out.printf(" "); 35 } 36 System.out.printf("\n"); 37 } 38... Shall we rearrange the codes in order to reduce the complexity of the main method? Zheng-Liang Lu Java Programming 199 / 227
1... 2 static int[] inputmethod() { 3 int[] record = new int[5]; 4 Scanner in = new Scanner(System.in); 5 int inputvalue; 6 do { 7 do { 8 System.out.println("Enter x? ( 1 to exit)"); 9 inputvalue = in.nextint(); 10 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 11 if (inputvalue >= 90) ++record[0]; 12 else if (inputvalue >= 80) ++record[1]; 13 else if (inputvalue >= 70) ++record[2]; 14 else if (inputvalue >= 60) ++record[3]; 15 else if (inputvalue >= 0) ++record[4]; 16 else System.out.println("End of input."); 17 } while (inputvalue!= 1); 18 in.close(); 19 return record; 20 } 21 22 23 Zheng-Liang Lu Java Programming 200 / 227
24 static void displayhistogram(int[] record) { 25 int total = 0; 26 for (int i = 0; i < cnt.length; i++) { 27 total += cnt[i]; 28 } 29 System.out.printf("Total: %d\n", total); 30 31 int[] tick = {0, 60, 70, 80, 90, 101}; 32 for (int i = 0; i < 5; i++) { 33 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 34 for (int j = 0; j < record[i]; j++) { 35 System.out.printf(" "); 36 } 37 System.out.printf("\n"); 38 } 39 } 40... Zheng-Liang Lu Java Programming 201 / 227
1... 2 public static void main(string[] args) { 3 int[] hist = inputmethod(); 4 displayhistogram(hist); 5 } 6... In practice, we make the main method as simple as possible. Zheng-Liang Lu Java Programming 202 / 227
Math Class The Math class contains the methods needed to perform basic mathematical functions. The Math class is public. All methods of Math class are public and static with two global constants Math.PI 1 and Math.E 2. The Math class provides common methods like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document of Math class can be found here. You are expected be able to read the document! 1 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 2 e is the base of the natural logarithm. It is approximately equal to 2.71828. Zheng-Liang Lu Java Programming 203 / 227
Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that a character is encoded using an integer. How to generate these characters randomly? Zheng-Liang Lu Java Programming 204 / 227
1... 2 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A + 1) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a + 1) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( 9 0 + 1) + 0 ); 12 } 13... Zheng-Liang Lu Java Programming 205 / 227
1... 2 public static void main (String[] args) { 3 for (int i = 1; i <= 10; ++i){ 4 int type = (int) (Math.random() 3); 5 switch (type) { 6 case 0: 7 System.out.printf("%c", getrandomuppercaseletter()); 8 break; 9 case 1: 10 System.out.printf("%c", getrandomlowercaseletter()); 11 break; 12 case 2: 13 System.out.printf("%c", getrandomdigitalcharacter()); 14 break; 15 } 16 } 17 } 18... Zheng-Liang Lu Java Programming 206 / 227
Method Overloading Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloading methods can make programs clearer and more readable. Name conflict is ok. Make sure the signatures differ; the overloaded methods have different parameter lists. Note that you cannot overload methods merely based on different modifiers or return types. Zheng-Liang Lu Java Programming 207 / 227
Example (Revisit) Printing stars Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats itself until the input number is negative. In addition, use * as the default symbol if the input is left blank. Zheng-Liang Lu Java Programming 208 / 227
1... 2 static void print(int n) { 3 for (int i = 1; i <= n; i++) { 4 for (int j = 1; j <= i; j++) { 5 System.out.printf(" "); 6 } 7 System.out.println(); 8 } 9 } 10 11 static void print(int n, String m) { 12 for (int i = 1; i <= n; i++) { 13 for (int j = 1; j <= i; j++) { 14 System.out.printf(m); 15 } 16 System.out.println(); 17 } 18 } 19... Zheng-Liang Lu Java Programming 209 / 227
1... 2 while (true) { 3 System.out.println("Enter n =? "); 4 n = Integer.parseInt(input.nextLine()); 5 if (n > 0) { 6 System.out.println("Enter a symbol? "); 7 m = input.nextline(); 8 if (m.equals("")) print(n); 9 else print(n, m); 10 } else { 11 System.out.println("Bye."); 12 break; 13 } 14 } 15... The method Integer.parseInt() converts the input string to an integer. The method nextline() returns a string from the keyboard. The method equals() is a String method used to compare if the two strings are identical. Zheng-Liang Lu Java Programming 210 / 227
Divide and Conquer When developing a program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose the original problem into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. Pros: easier to write, reuse, debug, test, modify, maintain, and better facilitating teamwork For most problems, do not write the entire program at once. 3 3 So you need more skills such that system analysis, project management, and software engineering. Zheng-Liang Lu Java Programming 211 / 227
Recursion 4 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is essentially repetition without a loop. 4 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 212 / 227
Try Fractal. Zheng-Liang Lu Java Programming 213 / 227
Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than and equal to n. Note that 0! = 1. For example, 5! = 5 4 3 2 1 = 5 4! = 120. Can you find the pattern? n! = n (n 1)! In general, f (n) = n f (n 1). Zheng-Liang Lu Java Programming 214 / 227
Write a program which determines n!. 1... 2 static int factorial(int n) { 3 if (n > 0) { 4 return n factorial(n 1); 5 } else { 6 return 1; // base case 7 } 8 } 9... Note that there must be a base case in recursion. Time complexity: O(n) Can you implement the same method by using a loop? Zheng-Liang Lu Java Programming 215 / 227
Zheng-Liang Lu Java Programming 216 / 227
Equivalence: Loop Version 1... 2 int y = 1; 3 for (int i = 1; i < = 10; i++) { 4 y = i; 5 } 6... Time complexity: O(n) One intriguing question is, Can we always turn a recursive method into the loop version of that? Yes, theoretically. 5 5 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 217 / 227
Remarks Recursion bears substantial overhead. So the recursive algorithm may execute a bit more slowly than the iterative equivalent. Additionally, a deeply recursive method depletes the call stack, which is limited, and causes stack overflow soon. Zheng-Liang Lu Java Programming 218 / 227
Exercise Fibonacci numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers can be defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. Zheng-Liang Lu Java Programming 219 / 227
Zheng-Liang Lu Java Programming 220 / 227
1... 2 static int fibrecursive(int n) { 3 if (n == 0) return 0; 4 else if (n == 1) return 1; 5 else return fibrecursive(n 1) + fibrecursive(n 2); 6 } 7... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. Time complexity: O(2 n ) (Why?!) Zheng-Liang Lu Java Programming 221 / 227
You can try an iterative approach for Fibonacci numbers. 1... 2 static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n < 2) { 5 return (n == 1)? y : x; 6 } else { 7 for (int i = 0; i < n; ++i){ 8 int tmp = x + y; 9 x = y; 10 y = tmp; 11 } 12 return y; 13 } 14 } 15... So it can be done in O(n) time. Can you find a linear recursion for Fibonacci numbers? Zheng-Liang Lu Java Programming 222 / 227
Computational Thinking 6 To think about computing, we need to be attuned to three fields: science, technology, and society. Computational thinking shares with mathematical thinking: the way to solve problems engineering thinking: the way to design and evaluating a large, complex system scientific thinking: the way to understand computability, intelligence, the mind and human behavior. 6 You should read this: http://rsta.royalsocietypublishing.org/content/366/1881/3717.full Zheng-Liang Lu Java Programming 223 / 227
Computational Thinking Is Everywhere! The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. The abstraction process, which is to decide what details we need to highlight and what details we can ignore, underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. Zheng-Liang Lu Java Programming 224 / 227
Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 225 / 227
Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 226 / 227
Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. Zheng-Liang Lu Java Programming 227 / 227