在替代密码Java中保留空格和标点符号

时间:2017-10-10 02:17:33

标签: java string encryption substitution

这个替换密码应该扰乱字母表并通过在正常字母表中查找消息中字母的位置并用拼写字母表中相同位置的字母替换它来编码消息。

所以像“ABC”这样的消息,使用像“QWERTYUIOPASDFGHJKLZXCVBNM”这样的混乱字母将成为“QWE”。

我的问题是标点符号和空格被其他字母取代,而且每个字母实际上并不对应于它的实际位置,它总是在它应该的位置之后的一个位置。第二部分有点令人费解,但不是一个大问题。

这是我的代码:

public static String cryptocodeM(String msg) {

    String[] alphabetArray = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    String newMsg = "";

    List<String> list = Arrays.asList(alphabetArray);
    Collections.shuffle(list);
    StringBuffer alph2 = new StringBuffer();

    for (int i = 1; i < list.size(); i++) {
        alph2.append(list.get(i));
    }

    String scramb = alph2.toString(); //the scrambled alphabet

    System.out.println(scramb);

    msg = msg.toUpperCase();

    for (int x = 0; x < msg.length(); x++) {
        char a = msg.charAt(x);  // the letters in msg

        int index = alphabet.indexOf(a) + 1; // index of the letters in the alphabet //when I don't add 1 here I get a runtime error saying "String out of range -1"  

        char b = scramb.charAt(index);  //finds letters in the same postion in the scrambled alphabet

        newMsg += b; //Adds up the letters
    }

    return newMsg;
}

此时,我不知道如何解决这个问题,因为我刚开始学习字符串。如果你能提供帮助我真的很感激。

1 个答案:

答案 0 :(得分:1)

index的{​​{1}}表示搜索未找到它。请参阅:String.indexOf()

尝试这样的事情:

-1

被修改

问题是,private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final char[] scramb = alphabet.toChararray(); public static String cryptocodeM(String msg) { if (null == msg || msg.isEmpty() ) return msg; final StringBuilder newMsg = new StringBuilder(msg.length()); shuffleArray(scramb); System.out.println(new String(scramb)); msg = msg.toUpperCase(); for (int x= 0; x < msg.length(); x++) { char a = msg.charAt(x); final int index = alphabet.indexOf(a); if (index > -1) a = scramb[index]; newMsg.append(a); } return newMsg.toString(); } public static void shuffleArray( char[] array ) { final Random rnd = new Random(); for ( int i = array.length - 1 ; i > 0 ; --i ) { final int index = rnd.nextInt( i + 1 ); // Simple swap final char a = array[index]; array[index] = array[i]; array[i] = a; } } vs char[],这是基元数组与对象数组...所以我只是从SO中查找了一个shuffle,发现了这个:Random shuffling of an array