I've written this simple program including a method for encoding a message (Caesar's cipher)... doesn't work though, and I think it has something to do with my if condition for letters that become offset past 'Z' (and thus reset to the beginning of the alphabet).
I've found other code for Caesar's cipher on the web which uses StringBuilders and other methods that I haven't learned yet. That's just great and I look forward to getting there one day, but in the meantime, what's going wrong with my code?
No need to give me the answer, but a hint would be much appreciated. :)
import java.util.*;
class Exercice4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a message:");
String msg = (sc.nextLine()).toUpperCase();
System.out.println("Enter a value for K:");
int k = sc.nextInt();
caesar(msg, k);
}
public static void caesar(String A, int B) {
char str[]=A.toCharArray();
String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i=0; i<A.length(); i++) {
for (int j=0; j<26; j++) {
if (alpha.charAt(j) == str[i]) {
if ((j+B)>25) {
str[i] = alpha.charAt(j + B - 26);
} else {
str[i] = alpha.charAt(j + B);
}
}
}
}
String code = new String (str);
System.out.println("Here is your encoded message: ");
System.out.println(A);
System.out.println(code);
}
}