栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java凯撒密码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java凯撒密码

使用

indexOf
效率不是很高…您可以对
char
值进行整数运算以获得其索引。

我在代码中添加了注释以解释更多信息,但这就是我想出的。

public class CaesarCipher {    // Rotate a character k-positions    public static char cipher(char c, int k) {        // declare some helping constants        final int alphaLength = 26;        final char asciiShift = Character.isUpperCase(c) ? 'A' : 'a';        final int cipherShift = k % alphaLength;        // shift down to 0..25 for a..z        char shifted = (char) (c - asciiShift);        // rotate the letter and handle "wrap-around" for negatives and value >= 26        shifted = (char) ((shifted + cipherShift + alphaLength) % alphaLength);        // shift back up to english characters        return (char) (shifted + asciiShift);    }    // Rotate a string k-positions    public static String cipher(String s, int k) {        StringBuilder sb = new StringBuilder();        for (int i = 0; i < s.length(); i++) { sb.append(cipher(s.charAt(i), k));        }        return sb.toString();    }    public static void main(String[] args) {        Scanner keyboard = new Scanner(System.in);        String password;        int key;        System.out.print("Please enter a password: ");        password = keyboard.nextLine();        do { System.out.print("Please enter a key between 1-25: "); key = keyboard.nextInt(); if (key < 1 || key > 25) {     System.out.printf(" The key must be between 1 and 25, you entered %d.n", key); }        } while (key < 1 || key > 25);        System.out.println("Password:t" + password);        String encryption = cipher(password, key);        System.out.println("Encrypted:t" + encryption);        System.out.println("Decrypted:t" + cipher(encryption, -key));    }}

输出应该是这样的

Please enter a password: ABCDEFGHIJKLMNOPQRSTUVWXYZPlease enter a key between 1-25: 1Password:   ABCDEFGHIJKLMNOPQRSTUVWXYZEncrypted:  BCDEFGHIJKLMNOPQRSTUVWXYZADecrypted:  ABCDEFGHIJKLMNOPQRSTUVWXYZ


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号