In my opinion, the main problem with your code is the duplication, here is my advices.
- Put the ui code out of the conditions.
The only issue there, if the choice is invalid, you can either show a default string, or throw an exception.
if (decision == 1) {
out = encrypt(field, shift);
} else if (decision == 2) {
out = decrypt(field, shift);
} else {
out = "Invalid choice!";
}
JTextArea msg = new JTextArea(out);
msg.setLineWrap(true);
msg.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(msg);
scrollPane.setPreferredSize(new Dimension(300, 300));
JOptionPane.showMessageDialog(null, scrollPane);
Or
if (decision == 1) {
out = encrypt(field, shift);
} else if (decision == 2) {
out = decrypt(field, shift);
} else {
throw new IllegalStateException("Invalid choice!")
}
JTextArea msg = new JTextArea(out);
msg.setLineWrap(true);
msg.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(msg);
scrollPane.setPreferredSize(new Dimension(300, 300));
JOptionPane.showMessageDialog(null, scrollPane);
- In the encrypt & decrypt, to create the string containing the result, i suggest that you use
java.lang.StringBuilder instead of concatening the String; you will gain some performance.
public static String decrypt(String text, int n) {
int x = 0;
int y = 0;
StringBuilder out = new StringBuilder(); //Empty string for result.
while (x < text.length()) {
if (text.charAt(x) > 64 && text.charAt(x) < 91) {
if (text.charAt(x) - n < 65) {
y = 26;
}
out.append(text.charAt(x) - n + y);
} else {
out.append(text.charAt(x));
}
x++;
y = 0;
}
return out.toString();
}
- In the encrypt & decrypt, extract the
text.charAt(x) in a variable, to remove the duplicates.
public static String decrypt(String text, int n) {
int x = 0;
int y = 0;
StringBuilder out = new StringBuilder(); //Empty string for result.
while (x < text.length()) {
final char currentChar = text.charAt(x);
if (currentChar > 64 && currentChar < 91) {
if (currentChar - n < 65) {
y = 26;
}
out.append(currentChar - n + y);
} else {
out.append(currentChar);
}
x++;
y = 0;
}
return out.toString();
}
- The encrypt and decrypt methods are pretty similar, you can probably merge them if you want.