Java中的凯撒密码转换?

时间:2019-02-10 16:31:44

标签: java

我试图模拟密码凯撒,但包括用户输入的数字和实现空间,但是,当我运行此程序时,没有预期的输出。这是我的代码,该如何处理?

import java.util.Scanner;
public class CaesarCipher {
public static void main(String[] args) {
    new CaesarCipher();
}

public CaesarCipher() {
    System.out.println("The encoded phrase is: " + encode("s", 0));
}

public String encode(String s,int n) { 
    //get user input for phrase and number shifted;
    Scanner sc =new Scanner (System.in);
    System.out.println("Enter a phrase to be encoded:");
    if (sc.hasNextLine()){
    s = sc.nextLine();

    System.out.println("Enter a number to shift each letter/number:");
    n = sc.nextInt();
    }
    sc.close();

    StringBuilder encoded = new StringBuilder();
    for (int i=0; i < s.length(); i++) {
        char letter = (char)(s.charAt(i));  
        int digit = (int)s.charAt(i);

        if (letter >= 'A' && letter <= 'Z') {
            int number = letter - 'A' + n;
            if(number<0)
                number=number+26;
            number=number%26;
            encoded.append((char)(number + 'A'));
        }
        else if(letter >= 'a' && letter <= 'z') {
            int num =  letter - 'a' + n;
            num = num%26;
            encoded.append((char)(num + 'a'));  
        }
        else if (digit>=0 && digit <=9) {
            encoded = 
        }
    }
    return encoded.toString();
}

这是我想要的输出:

Enter your phrase:
>> 3 cats is nice!
Enter shift for phrase:
>> 1
Your encrypted code is: 4 dbut jt ojdf!

0 个答案:

没有答案