Program 6 encryption method Encode decode a string












































- Slides: 44
Program 6 encryption method: // Encode / decode a string by shifting the characters. // It cyclically shifts just the alphabetic characters. // input: a string and a positive shift amount 1 to 25 // output: prints the shifted string and a newline public static void cipher(String msg, int shift) { for (int i = 0; i < msg. length(); i++) { char c = msg. char. At(i); if (Character. is. Lower. Case(c)) { c += shift; if (c > 'z') { c -= 26; } } else if (Character. is. Upper. Case(c)) { c += shift; if (c > 'Z') { c -= 26; } } // otherwise leave it alone System. out. print(c); } System. out. println(); }
Review • If something goes wrong, such as an invalid parameter value, Java allows us to "throw an exception" which will print an error message and terminate the program. if (n < 0) { throw new Illegal. Argument. Exception("negative n"); } • You can return from anywhere within a method, but you must make sure that every path through the method returns a value. public static int index. Of(String s, char c) { for (int i = 0; i < s. length(); i++) { if (s. char. At(i) == c) { return i; } } return -1; // not found }
Building Java Programs Chapter 5: Program Logic and Indefinite Loops while loops reading: 5. 1 3
definite loop: One that executes a known number of times. The for loops we have seen so far are definite loops. • We often use language like, "Repeat these statements N times. " "For each of these 10 things, . . " • Examples: o. Print "hello" 10 times. o. Find all the prime numbers up to an integer n. o. Print each odd number between 5 and 127.
indefinite loop: One where it is not obvious in advance how many times it will execute. We often use while loops for indefinite loops. We use language like: "Keep looping as long as or while this condition is still true. " "Don't stop repeating until the following happens. " Examples: Prompt the user until they type a non-negative number. Print random numbers until a prime number is printed. Continue looping while the user has not typed "n" to quit.
The while loop statemen t • while loop: Executes a group of statements as long as a condition is true. – well suited to writing indefinite loops • The while loop, general syntax: while (<condition>) { <statement(s)> ; } • Example: int number = 1; while (number <= 200) { System. out. print(number + " "); number *= 2; } – OUTPUT: 1 2 4 8 16 32 64 128 6
while loop control flow diagram
public class While. Gus { // This program finds out how many days it takes Gus to receive at // least $100. It does this 20 times and then finds the average # of days. public static void main(String[] args) { int total = 0; int amount, days; for ( int rep = 1; rep <=20 ; rep++) { amount = 0; days = 0; while (amount < 100 ) { amount = amount + (int) (Math. random()* 3) + 1; days++; } System. out. println("It took " + days + " days for Gus to get $" + amount); total += days; } System. out. println("After 20 runs, Gus averaged " + total/20. 0 + " days to get at least $100"); } }
It took 49 days for Gus to get $100 It took 46 days for Gus to get $100 It took 55 days for Gus to get $102 It took 46 days for Gus to get $100 It took 51 days for Gus to get $101 It took 49 days for Gus to get $100 It took 54 days for Gus to get $100 It took 50 days for Gus to get $100 It took 45 days for Gus to get $100 It took 50 days for Gus to get $101 It took 51 days for Gus to get $100 It took 52 days for Gus to get $100 It took 47 days for Gus to get $101 It took 55 days for Gus to get $102 It took 49 days for Gus to get $101 It took 52 days for Gus to get $101 It took 49 days for Gus to get $101 It took 50 days for Gus to get $101 After 20 runs, Gus averaged 50. 2 days to get at least $100
Another example while loop • Find and print a number's first factor other than 1: Scanner console = new Scanner(System. in); System. out. print("Type a number: "); int number = console. next. Int(); int factor = 2; while (number % factor != 0) { factor++; } System. out. println("First factor: " + factor); • Example execution: Type a number: 91 First factor: 7
Equivalence of for loops and while loops • Any for loop of the following form: for (<initialization>; <condition>; <update>) { <statement(s)>; } can be replaced by a while loop of the following form: <initialization>; while (<condition>) { <statement(s)>; <update>; }
Example of equivalent for / while loops • for loop: for (int i = 1; i <= 10; i++) { System. out. println(i + " squared = " + (i * i)); } • while loop: int i = 1; while (i <= 10) { System. out. println(i + " squared = " + (i * i)); i++; }
public class For. Gus { // This program finds out how many days it takes gut to receive at // least $100. It does this for 20 times and then finds the average public static void main(String[] args) { int total = 0; int days, amount; for ( int rep = 1; rep <=20 ; rep++) { days = 0; for ( amount = 0; amount < 100 ; amount = amount + (int) (Math. random()* 3) + 1){ days++; } System. out. println("It took " + days + " days for gus to get $" + amount); total += days; } System. out. println("After 20 runs, Gus averaged " + total/20. 0 + " days to get at least $100"); } }
It took 50 days for Gus to get $101 It took 51 days for Gus to get $100 It took 56 days for Gus to get $101 It took 46 days for Gus to get $101 It took 52 days for Gus to get $101 It took 56 days for Gus to get $100 It took 45 days for Gus to get $102 It took 51 days for Gus to get $100 It took 52 days for Gus to get $100 It took 46 days for Gus to get $100 It took 48 days for Gus to get $101 It took 57 days for Gus to get $101 It took 51 days for Gus to get $101 It took 52 days for Gus to get $102 It took 59 days for Gus to get $101 It took 48 days for Gus to get $100 It took 51 days for Gus to get $100 It took 45 days for Gus to get $100 After 20 runs, Gus averaged 51. 0 days to get at least $100
Activity: • Write a method named digit. Sum that accepts an integer as a parameter and returns the sum of the digits of that number. • e. g. digit. Sum(29107) • calculates: 2+9+1+0+7 • returns: 19 • You may assume that the number is non-negative. Hints: – Use the % operator to extract the last digit of a number. –If we do this repeatedly, when should we stop?
Activity answer: public static int digit. Sum(int n) { int sum = 0; while (n > 0) { sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } return sum; }
Sentinel value • We want to stop when a certain value is read in. It should be a value that is not in the range of possible values. Ex. Use -1 as sentinel. Scanner console = new Scanner(System. in); int sum = 0; System. out. print("Enter a number (-1 to quit): "); int input. Number = console. next. Int(); while (input. Number != -1) { sum += input. Number; // moved to top of loop System. out. print("Enter a number (-1 to quit): "); input. Number = console. next. Int(); } System. out. println("The total was " + sum); 17
The Random class is used to generate pseudo-random numbers. • Class Random is found in the java. util package. import java. util. *; • To create a Random number generator object: Random rand = new Random(); • Then use it to create random numbers: Method next. Int() next. Int(max) next. Double() Description random integer over entire range +/- 2 billion random integer from 0 to max-1 random double in [0. 0, 1. 0) – Example: Random rand = new Random(); int random. Number = rand. next. Int(10); // random. Number has a random value between 0 and 9
Examples • Generate a random number from 0 to 9 Random rand = new Random(); int n = rand. next. Int(10); • Generate a random number from 1 to 20 n = rand. next. Int(20) + 1; • To get a number in arbitrary range [min, max]: next. Int(<size of the range>) + min where <size of the range> equals max - min + 1 – Example: A random integer from 5 to 10 inclusive: int n = rand. next. Int(6) + 5;
Activity • Given the following declaration, how would you get: Random rand = new Random(); –A random number between 0 and 100 inclusive? A random number between 1 and 100 inclusive? A random number between 4 and 17 inclusive?
Example using Random in text processing • Code to pick a random lowercase letter: char letter = (char) ('a' + rand. next. Int(26)); – Code to pick a random character from a string (in this case, a random vowel): String vowels = "aeiou"; char vowel = vowels. char. At(rand. next. Int(vowels. length());
Other examples • next. Double returns a double in [0. 0, 1. 0) • To get a double in a different range, multiply and/or add • Example: Get a random angle between in [45. 0, 90. 0) double angle = rand. next. Double()*45. 0 + 45. 0; • Random can be used to pick between arbitrary choices – Code to pick a red, green, or blue color: int r = rand. next. Int(3); if (r == 0) { g. set. Color(Color. RED); } else if (r == 1) { g. set. Color(Color. GREEN); } else { g. set. Color(Color. BLUE); }
Boolean logic reading: 5. 2 23
boolean type • boolean is a primitive type to represent logical values. • A boolean expression produces either true or false. • The <condition> in if statements and for loops is boolean. • Examples: boolean minor = (age < 21); boolean pass = (total >= 60); boolean taking. COS 160 = true; if (minor) { System. out. println("Can't purchase alcohol!"); } • You can create boolean variables, pass boolean parameters, return boolean values from methods, . . .
Logical operators && || ! • Boolean expressions can use logical operators: Operator Description Example Result && (9 != 6) && (2 < 3) true and || (2 == 3) || (-1 < 5) true or not ! !(7 > 0) false • Truth tables of each operator used with boolean values p and q: p true q true false true p && q p || q true false 25 true false p true !p false true
Logical Operators Operator && Meaning Example AND (a < b) && (b < c) || OR (a < b) || (a < c) ! NOT !minor
Example • You can not write: if (1 <= x <= 10) { System. out. println("In range"); } • But you can write: if (1 <= x && x <= 10) { System. out. println("In range"); }
if (age > 5 && age <= 18) { System. out. println("Why aren't you in school"); } if (hour < 7 || day. equals("Sunday")){ System. out. println("Let me sleep!"); } if (!minor && Husky. Buck$ > 3) { System. out. println("Here is your beer"); }
Java Operator Precedence Desciption Operators unary operators ! ++ multiplicative additive + relational equality + * / > >= - % < == -- <= != logical AND && logical OR || assignment = += -= *= %= &&= ||=
Boolean logic questions • What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; – – – y < x && y <= z x % 2 == y % 2 || x % 2 == z % 2 x <= y + z && x >= y + z !(x < y && x < z) (x + y) % 2 == 0 || !((z - y) % 2 == 0) • Answers: true, false, true, false 30
Review • while loop – used for indefinite loops where we don't know the loop bounds ahead of time public static int digit. Sum(int n) { int sum = 0; while (n > 0) { sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } return sum; } • The Random class is used to generate sequences of random numbers. Random rand = new Random(); int n = rand. next. Int(10); // random value from 0 to 9
Activity – evaluate these boolean expressions boolean a = true; boolean b = false; boolean c = true; • • a && !b b && !c !a || !b a && b || c a || b && c a && b && c a || b || c
Short Circuit Evaluation • When faced with a multiple part logical expression, Java stops evaluating as soon as it has enough information to determine the answer. • if ( (a < b) && (b < c) ) part-1 part-2 If part-1 is false it doesn't need to evaluate part-2. if ( (a < b) || (c < b) ). . . part-1 part-2 If part-1 is true it doesn't need to evaluate part-2.
Occasionally this is very useful. public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } return s. substring(start, end); } public static void main(String[] args) { String s = first. Word(" test string "); System. out. println(s); } start t e s t end s t r i n g
public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } return s. substring(start, end); } public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } start t e s t i m o n i a l end
public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } return s. substring(start, end); } public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } start t e s t i m o n i a l end
public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (start < s. length() && s. char. At(start) == ' ') { start++; } // find end - move past word to next space int end = start; while (end < s. length() && s. char. At(end) != ' ') { end++; } return s. substring(start, end); } public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } start t e s t i m o n i a l end
Methods that return boolean • There are methods in Java that return boolean values. – A call to one of these methods can be used as a <condition> in a for loop, while loop, or if statement. • Examples: Scanner console = new Scanner(System. in); System. out. print("Type your name: "); String line = console. next. Line(); if (line. starts. With("Dr. ")) { System. out. println(“Do you support health care reform? ? "); } else if (line. ends. With(", Esq. ")) { System. out. println(“Is tort reform necessary? "); } 38
String boolean methods • The following String methods return boolean values: Method equals(String) Description whether two strings contain exactly the same characters equals. Ignore. Case(String) whether two strings contain the same characters, ignoring upper vs. lower case differences starts. With(String) whether one string contains the other's characters at its start ends. With(String) whether one string contains the other's characters at its end 39
Writing boolean methods • Methods can return a boolean result. public static boolean both. Odd(int n 1, int n 2) { if (n 1 % 2 != 0 && n 2 % 2 != 0) { return true; } else { return false; } } • Calls to such methods can be used as conditions: if (both. Odd(7, 13)) {. . . } More advanced: return n 1 % 2 != 0 && n 2 % 2 != 0; 40
do/while loop • The do/while loop, general syntax: do { <statement(s)> ; } while (<condition>); • The do/while loop executes statements repeatedly while a condition is true, testing it at the end of each repetition. • It is similar to a while loop, except that its body statement(s) will always execute at least once. • Example – get an odd random number do { x = rand. next. Int(); } while (x%2 != 1); System. out. printf("Your odd number is %d", x);
do / while control flow
Another example: public static int smallest. Digit(int n) { int smallest = 9; // start high do { int digit = n%10; smallest = Math. min(smallest, digit); n /= 10; } while (n > 0); return smallest; } public static void main(String[] args) { int i = smallest. Digit(43658); System. out. println(i); } Output: 3
Activity Write a method to play the guess the secret number game Try to guess my number 1 -100. Guess? 50 too low Guess? 75 too low Guess? 85 You got it! Here is the start of the method. Use a do / while loop. public static void guess(Scanner console, int secret. Num) { System. out. println("Try to guess my number 1 -100. "); int guess; . . .