I've wrote a little program that encrypts text by using the caesar-cipher. Also it contains a little GUI, created by using swing. Here's the full code:
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
public class caesar {
public static void main(String[] args) {
String field, text;
field = JOptionPane.showInputDialog("Please enter text:");
field = field.replaceAll("[^a-zA-Z]+", "");
field = field.toUpperCase();
int shift;
String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:");
shift = Integer.parseInt(shift_String);
String d = JOptionPane.showInputDialog("Encrypt (1) or decrypt (2):");
int decision = Integer.parseInt(d);
String out;
if(decision==1) {
out = encrypt(field, 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);
}
if(decision==2) {
out = decrypt(field, 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);
}
}
//Encryption
public static String encrypt(String text, int n) {
int x = 0;
int y = 0;
String out = ""; //Empty string for result.
while (x < text.length()) {
if (text.charAt(x) > 64 && text.charAt(x) < 91) {
if (text.charAt(x) + n > 90) {
y = 26;
}
out = out + (char) (text.charAt(x) + n - y);
} else {
out = out + text.charAt(x);
}
x++;
y = 0;
}
return out;
}
//Decryption
public static String decrypt(String text, int n) {
int x = 0;
int y = 0;
String out = ""; //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 = out + (char) (text.charAt(x) - n + y);
} else {
out = out + text.charAt(x);
}
x++;
y = 0;
}
return out;
}
}
My question now is: How to improve this code?
I mean, it does what it is supposed to do, but it's not really great code.