java 凯撒密码
写一个关于凯撒密码的程序。要求可以输入正整数和复数,包括大小写
例
Enter shift: 4
Enter message: HELLO
Encode message: LIPPS
另一个是只要求翻译大写字母不翻译小写字母
(小弟初学,跪求大神帮忙,在线等)
import javax.swing.*; public class CaesarCipher { public static void main(final String[] args) { try { Integer enterShift = Integer.valueOf(JOptionPane.showInputDialog("Enter shift:")); String enterMessage = JOptionPane.showInputDialog("Enter message:"); String encodeMessage = CaesarCipher.encode(enterMessage, enterShift); JOptionPane.showMessageDialog(null, encodeMessage, "Encode message:", JOptionPane.PLAIN_MESSAGE); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Shift must be integer!", "Warning:", JOptionPane.WARNING_MESSAGE); } } public static String decode(String enc, int offset) { return encode(enc, -offset); } public static String encode(String enc, int offset) { offset = offset % 26 + 26; StringBuilder encoded = new StringBuilder(); for (char i : enc.toCharArray()) { if (Character.isUpperCase(i)) { encoded.append((char) ((i - 'A' + offset) % 26 + 'A')); }/* else if (Character.isLowerCase(i)) { encoded.append((char) ((i - 'a' + offset) % 26 + 'a')); }*/ else { encoded.append(i); } } return encoded.toString(); } }