Unit 4 HW - Iteration & Caeser Cipher
- An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
- It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.
- for, while, ect
- sequence of instructions or code being repeated until a specific end result is achieved
- MacroMonkeys repo with caesar cipher shifts
- Iteration is crucial to making coding simpler and less convoluted
- Exam weights Iteration as 17.5-22.5% of the test, with 7-9 MC and part of FRQ 1
Nested Loop
- nested for loop places one for loop inside another for loop
- inner loop repeats for every iteration of the outer one
int i = 5450000;
int years = 0;
while (i < 30000000){ //hack 2 with while loop
i *= 1.05;
years += 1;
}
System.out.println(years);
FOR LOOPS
- the test condition is checked each time through the loop and the loop continues as long as the condition is true
- the loop control variable change is done at the end of each execution of the body of the loop
- When the loop condition is false, execution will continue at the next statement after the body of the loop.
public class ForLoops { //hack 2
public static void main(String[] args) {
for (int x = 10; x <= 15; x++) { //for loop iteration
System.out.println(x);
}
}
}
ForLoops.main(null);
public class CaesarCipher {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", //creates a string list for lowercase letters
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String[] capitalLetters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", //uppercase
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
static String message1 = "Kfzb gly!";
static String message2 = "zlab zlab zlab";
static String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp"; //sets 3 different messages
String letterIndividual = "";
public CaesarCipher(String msg) {
for (int i = 0; i < msg.length(); i++) {
letterIndividual = msg.substring(i, i+1);
//iteration through i++ and j++
if (letterIndividual.equals(" ")) {
System.out.print(" ");
} //if statement
if (letterIndividual.equals("!")) {
System.out.print("!");
}
for (int j = 0; j < letters.length; j++) {
if (letterIndividual.equals(letters[j])) {
System.out.print(letters[(j+3)%26]);
} //adds three and then uses modulus function
if (letterIndividual.equals(capitalLetters[j])) {
System.out.print(capitalLetters[(j+3)%26]); //key shift
}
}
}
System.out.println("");
}
public static void main(String[] args) { //prints the decoded messages
CaesarCipher decode = new CaesarCipher(message1);
CaesarCipher decode2 = new CaesarCipher(message2);
CaesarCipher decode3 = new CaesarCipher(message3);
}
}
CaesarCipher.main(null)