Lesson 4 Homework - Iteration
public class WhileLoops {
public double money = 0;
public double profit = 5450000;
public double goal = 30000000;
public double years = 0;
public void Calc() {
while (this.money < this.goal) {
this.money = this.money + this.profit;
this.profit = this.profit * 1.05;
this.years = this.years + 1;
}
System.out.println(this.years);
}
public static void main(String[] args) {
WhileLoops obj = new WhileLoops();
obj.Calc();
}
}
WhileLoops.main(null);
public class ForLoops {
public double temp = 0;
public void Calc() {
System.out.println("Numbers 10-15");
for (int x = 10; x <= 15; x++) {
System.out.println(x);
}
System.out.println("Convert temperature");
for (int x = 0; x<=100; x+=10) {
temp = 0;
temp = x + 273.15;
System.out.println(x + "c -> " + temp + "k");
}
}
public static void main(String[] args) {
ForLoops obj = new ForLoops();
obj.Calc();
}
}
ForLoops.main(null);
public class CaesarCipher {
public 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"};
public String temp;
// Method which takes a string and swaps a character
static char[] swap(String str, int i, char j)
{
char ch[] = str.toCharArray();
ch[i] = j;
return ch;
}
public String Calc(String message) {
temp = message;
// Looping through each character in the message
for (int i=0; i<temp.length(); i++) {
// Cast the character to ascii to make substitutions much more efficient
int ascii = (int) temp.charAt(i);
// Letters at the end of the alphabet behave differently, so we create two separate conditionals
if (ascii > 64 && ascii < 88 || (ascii > 96 && ascii < 120)) {
ascii = ascii + 3;
String tempSwap = new String(swap(temp, i, (char) ascii));
temp = tempSwap;
}
// This is for the last three letters of the alphabet
else if (ascii > 87 && ascii < 91 || ascii > 119 && ascii < 123) {
ascii = ascii - 23;
String tempSwap = new String(swap(temp, i, (char) ascii));
temp = tempSwap;
}
}
return temp;
}
public static void main(String[] args) {
CaesarCipher cipherCalc = new CaesarCipher();
String message1 = "Kfzb gly!";
String message2 = "zlab zlab zlab";
String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
System.out.println(cipherCalc.Calc(message1));
System.out.println(cipherCalc.Calc(message2));
System.out.println(cipherCalc.Calc(message3));
}
}
CaesarCipher.main(null);