I've now used the tips, you can find here and there, to improve my code:
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
public class CaesarCipher {
enum WhatToDo {ENCRYPT, DECRYPT};
public static void main(String[] args) {
String UserInput = JOptionPane.showInputDialog("Please enter text:");
String text = UserInput.replaceAll("[^a-zA-Z]+", "");
text = text.toUpperCase();
String message = "Please enter shift to the right:";
int shift = findShift(message);
String out = "";
message = "Encrypt or decrypt?";
out = MakeDecision(message, text, shift);
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);
}
public static int findShift(String msg) {
String UserInput = JOptionPane.showInputDialog(msg);
int shift;
try {
shift = Integer.parseInt(UserInput);
}
catch (NumberFormatException e) {
shift = findShift("Please enter shift as a number:");
}
return shift;
}
public static String MakeDecision(String message, String text, int shift) {
String UserInput = JOptionPane.showInputDialog(message);
UserInput = UserInput.toUpperCase();
String out = "";
if(WhatToDo.ENCRYPT.name().equals(UserInput) == true) {
boolean test = true;
out = EncryptOrDecrypt(text, shift, test);
}
else if(WhatToDo.DECRYPT.name().equals(UserInput) == true) {
boolean test = false;
out = EncryptOrDecrypt(text, shift, test);
}
else {
message = "Illegal Choice! Encrypt or decrypt?";
out = MakeDecision(message, text, shift);
}
return out;
}
//Encryption
public static String EncryptOrDecrypt(String text, int n, boolean test) {
int count = 0;
int alphabetLength = 0;
int decryptFactor = 1;
if(!test) {
decryptFactor = -1;
}
StringBuilder out = new StringBuilder(); //Empty string for result.
while (count < text.length()) {
final char currentChar = text.charAt(count);
if (currentChar >= 'A' && currentChar <= 'Z') {
if (currentChar + n > 'Z') {
alphabetLength = 26;
}
out.append((char)(currentChar + (n*decryptFactor) - (alphabetLength*decryptFactor)));
}
else {
out.append(currentChar);
}
count++;
alphabetLength = 0;
}
return out.toString();
}
}
Do you think that this now is good code? Do you have any tips for further improvement?
EncryptOrDecrypt
, why is theif (currentChar >= 'A' && currentChar <= 'Z') {
test there? Aren't all non-alphabetics filtered out and everything set to uppercase? \$\endgroup\$