Unit 4 Iteration Homework
Unit 4 Iteration
public class CaesarCipher {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "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", "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";
String letterIndividual = "";
public CaesarCipher(String msg) {
for (int i = 0; i < msg.length(); i++) {
letterIndividual = msg.substring(i, i+1);
if (letterIndividual.equals(" ")) {
System.out.print(" ");
}
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]);
}
if (letterIndividual.equals(capitalLetters[j])) {
System.out.print(capitalLetters[(j+3)%26]);
}
}
}
System.out.println("");
}
public static void main(String[] args) {
CaesarCipher decode = new CaesarCipher(message1);
CaesarCipher decode2 = new CaesarCipher(message2);
CaesarCipher decode3 = new CaesarCipher(message3);
}
}
CaesarCipher.main(null)
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This for-loop was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing array or collections. This loop also makes the code more readable and reduces the chance of bugs in the code.
for(data-type variable : array | collection)
{
// Code to be executed
}
The while loop loops through a block of code as long as a specified condition is true
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
If a loop exists inside the body of another loop, it's called a nested loop.
class Main {
public static void main(String[] args) {
int weeks = 3;
int days = 7;
// outer loop prints weeks
for (int i = 1; i <= weeks; ++i) {
System.out.println("Week: " + i);
// inner loop prints days
for (int j = 1; j <= days; ++j) {
System.out.println(" Day: " + j);
}
}
}
}