// APS101, Winter 2009: Lecture 20 (Mar. 2) // // Monitor the A2 FAQ page for announcements about TA office hours this week // (most likely Wed. 2-3pm, in BA4177, and next Mon. 12-2pm) // // Tomorrow's tutorial is IMPORTANT - will help you with A2: // - binary representation // - exclusive-or // - the encryption algorithm // - other hints // // Note about converting char values to ASCII: it's easy. char x = 'a' (int) x int x = 'a' // this works as well // Review: last time we wrote the HighLow game // it wasn't user-friendly enough, so we wrote a // Graphical User Interface (GUI) for it. // Then, we added a while loop. HighLowGUI2 h = new HighLowGUI2(10) h.makeGuess() // need to do this only once now! // exercise: modify the code so that there is a limit on how many guesses a player gets. // what if we want to print the squares of numbers from 1 to 4: System.out.println(1 * 1); System.out.println(2 * 2); System.out.println(3 * 3); System.out.println(4 * 4); // what if we want to do it for 1 to 300? // we need a loop! WhileDemo.printSquares(10) // how about printing a String backwards: WhileDemo.printRString("ABCD") String s = WhileDemo.printRString("ABCD"); // what's wrong? how do we store the result? // we need to write a method that reverses the String and returns the result as a String. // reversing a String: "abcd" -> "dcba" // starting from the end, we go backwards and concatenate characters: // "d" // + "c" // // + "b" // + "a" // end index: length - 1 // character at position i: s.charAt(i) WhileDemo.reverseString("ABCD") String s = WhileDemo.reverseString("ABCD") // let's do it another way (there are many different ways to do it) WhileDemo.reverseString2("ABCD") // for loops: for (initialization; condition; update statement) { body; } * for loops are good to use when you know the range * // now, let's do the String reversal using a for loop. ForDemo.reverse("ABCD") (take a look at the tester for reverse in ForDemo - TesterFor.java. we didn't cover this in lecture, but it's very simple!) // palindromes: ex. "wow", "lol", "racecar" // let's write a method that checks whether a String is a palindrome by // testing whether the given String is equal to its reverse. WhileDemo.isPalindrome("racecar") // true WhileDemo.isPalindrome("haha") // false WhileDemo.isPalindrome("") // also true... we want it to be false WhileDemo.isPalindrome("Racecar") // false... we want this to be true // use String method toLowerCase() to fix this WhileDemo.isPalindrome("Racecar ") // false, because of the extra space at the end // use the trim() method to get rid of preceding and trailing whitespace * also, take a look at methods countChars and mystery in WhileDemo - we'll go over them tomorrow *