Since I am new to Java, I wanted to see if there were better ways of answering the same question. Are parts of my code redundant or maybe there's an easier way to get the same result?
[Problem J4: Big Bang Secrets][1]. The encoding algorithm is a Caesar cipher with a shift (_S_) that depends on a parameter (_K_) and its position in the word (_P_, where _P_ = 1 for the first letter of each word): _S_ = 3 _P_ + _K_. For example, when _K_ = 3, `ZOOM` is encoded as `FXAB`:
- \$S_1 = 3 \times 1 + 3 = 6\$, so `Z` → `F`
- \$S_2 = 3 \times 2 + 3 = 9\$, so `O` → `X`
- \$S_3 = 3 \times 3 + 3 = 12\$, so `O` → `A`
- \$S_4 = 3 \times 4 + 3 = 15\$, so `M` → `B`
The challenge is to write a decoder. The first line of input contains _K_ (_K_ < 10). The second line contains the encoded message, containing up to 20 characters in uppercase.
public class Decoder {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
int k = Integer.parseInt(in.readLine());
String word = in.readLine();
char[] cArray = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
char out = (char) ((cArray[i]) - (((3 * (i + 1)) + k) % ('Z' - 'A')));
if (out < 'A') {
char wrap = (char) (('Z' + 1) - ('A' - out));
System.out.print(wrap);
} else {
System.out.print(out);
}
}
} catch (IOException e) {
System.out.println("Error");
}
}
}
[1]: http://cemc.uwaterloo.ca/contests/computing/2012/stage1/juniorEn.pdf