2

我正在尝试学习 Java,并希望有人能指出我正确的方向。我正在尝试在 java 中构建一个凯撒密码程序,并且我正在尝试使用自定义字符串,并且无法引用由自定义字符串组成的数组(例如,移位为 1,'a' 会变成'b','z'会变成'A','?'会变成'@',等等;实际的自定义字符串在程序的数组中列出)。我现在拥有程序的方式,它可以转换 az 和 AZ,但我需要它继续转换为特殊字符。我知道我现在没有引用我的字符串,但不知道如何让它这样做!任何帮助深表感谢!

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;
}
}
4

1 回答 1

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;
}
于 2012-09-02T21:09:40.843 回答