引用Caesar Cipher中数组的字符

时间:2012-09-02 20:55:57

标签: java arrays string reference

我正在努力学习Java,并希望有人能指出我正确的方向。我试图在java中构建一个caesar密码程序,我正在尝试使用自定义字符串,并且无法引用由自定义字符串组成的数组(例如,移位为1,'a'会成为'b','z'将成为'A','?'将成为'@',依此类推;实际的自定义字符串列在程序中的数组中)。我现在拥有该程序的方式,它可以移动a-z和A-Z,但我需要它继续转移到特殊字符。我知道我现在没有引用我的字符串,但我不确定如何让它这样做!非常感谢任何帮助!

package caesarcipher;

import java.util.Scanner;

public class Caesarcipher
{
public static void main(String[] args)
{
    Scanner scan = new Scanner (System.in);

    System.out.println("Please enter the shift you would like to use:");

    String shift = scan.next();

    int shiftvalue = Integer.parseInt(shift);

    System.out.println("The shift will be: " + shiftvalue);

    System.out.println("Please enter text:");

    String text = scan.next();

    String ciphertext = encryptCaesar(text, shiftvalue);

    System.out.println(ciphertext);
}
private static String encryptCaesar(String str, int shiftvalue)
{
        if (shiftvalue < 0) 
        {
            shiftvalue = 81 - (-shiftvalue % 81);
        }
    String result = "";
        for (int i = 0; i < str.length(); i++) 
        {
        char ch = encryptCharacter(str.charAt(i), shiftvalue);
        result += ch;
        }
    return result;
}
private static char encryptCharacter(char ch, int shiftvalue) 
{
    String[] values = {"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", "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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " ", "!", "\\", "\"", "#", "$", "%", "&", "'", "(", ")", ",", "-", ".", "/", ":", ";", "?", "@"};  

    if (Character.isLowerCase(ch))
        {
            ch = (char) ('a' + (Character.toLowerCase(ch) - 'a' + shiftvalue) % 81);
        }
    else if (Character.isUpperCase(ch))
        {
            ch = (char) ('a' + (Character.toUpperCase(ch) - 'a' + shiftvalue) % 81);
        }
    return ch;
}
}

1 个答案:

答案 0 :(得分:0)

您可以执行此操作来移动字母输入。它适用于大于26的shiftvalue。

public static String encrypt(String str, int shift)
{
String ciphered="";
char[] ch=str.toCharArray();
int exact=shift%26;
    if(exact<0)
    exact+=26;
int rotate=shift/26;
int i=0;
while(i<ch.length)
{
    if(Character.isLetter(ch[i]))
    {
        int check=Character.isUpperCase(ch[i])?90:122;
        ch[i]+=exact;
        if(check<ch[i])
        ch[i]=(char)(ch[i]-26);
        if(rotate%2==0)
        {
            if(Character.isLowerCase(ch[i]))
            ch[i]=Character.toUpperCase(ch[i]);
            else
            ch[i]=Character.toLowerCase(ch[i]);     
        }
    }   
        ciphered+=ch[i++];          
    }
return ciphered;
}