RosettaCodeData/Task/Caesar-cipher/Java/caesar-cipher.java

31 lines
977 B
Java
Raw Normal View History

2013-04-10 12:38:42 -07:00
public class Cipher {
2015-02-20 00:35:01 -05:00
public static void main(String[] args) {
2013-04-10 12:38:42 -07:00
2015-02-20 00:35:01 -05:00
String str = "The quick brown fox Jumped over the lazy Dog";
2013-04-10 12:38:42 -07:00
2015-02-20 00:35:01 -05:00
System.out.println( Cipher.encode( str, 12 ));
System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
}
public static String decode(String enc, int offset) {
return encode(enc, 26-offset);
}
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
2013-04-10 12:38:42 -07:00
}