Java Caesar shift 字符打印失败



>我正在尝试开发一个非常基本的程序(我稍后会添加)对用户输入的文本执行凯撒移位。

我有很多工作,但是当我尝试打印出"加密"字符串时,它不起作用。我正在使用Netbeans IDE,它只是打印出一个空白值。我已经添加了额外的打印语句来进行错误检查,我相信我的"加密"(即更改字符)正在正确发生,但是当我将其重新转换为字符时,有些东西失败了。我的代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package forpractice;
import java.util.*;
import java.util.Scanner;
class CaesarShift {
//    public String encrypt(String[] plainText){
//        return null;
//        
//        
//        
//    }
public static void main(String[] args){
// Variable declarations needed for the entire program
Scanner myScan = new Scanner(System.in);
System.out.println("Please input a string of characters to encrypt: ");
String plainText = myScan.nextLine();
String convertedText = plainText.toLowerCase();
char[] plainTextArray = convertedText.toCharArray();
ArrayList<Character> encryptedTextArray = new ArrayList<>();
String encryptedString = new String();

int currValue;
char curr;
char curr1;
char newCurr;
int newCurrValue;
// Variable declarations needed for the entire program
// Loop through the array, convert to all lowercase, and encrypt it
for (int i = 0; i < plainTextArray.length; i++){
curr = plainTextArray[i];
System.out.println("Current character: " + plainTextArray[i]);
currValue = (int) curr;
System.out.println("Current character value: " + currValue);
newCurrValue = ((currValue-3) % 26);
System.out.println("Encrypted character value: " + newCurrValue);
newCurr = (char) newCurrValue;
System.out.println("Encrypted character: " + newCurr);
encryptedTextArray.add(newCurr);
} //end for
System.out.println("Here is the algorithm :");
System.out.println("***************");
System.out.println("Your Plaintext was: " + plainText);
System.out.println("Your encrypted text was: ");
for (int i = 0; i < encryptedTextArray.size(); i++){
encryptedString += encryptedTextArray.get(i);
}
System.out.println("***************");

} //end psvm       
} //end class

您的任何建议或意见将不胜感激。我没有找到任何关于这个特定问题的例子。谢谢。

密切关注 ASCII 表和您的表达式

newCurrValue = ((currValue-3) % 26);

您从当前值中减去 3,然后取 mod 26,这保证您的结果在 0 到 26 的范围内。如果您在表中查找它,您会发现既没有要za的值,也没有要ZA的值。实际上,所有这些字符要么是隐形的,要么是空白的。

下面的示例演示了小写字符的正确用法:

newCurrValue = ((currValue - 'a') % 26 - 3); // 3 is your shift value
// if the result is negative, simply add 26 (amount of smallercase characters)
if (newCurrValue < 0) {
newCurrValue += 26;
}
newCurrValue += 'a'; // add 'a' again, to be within 'a' - 'z'

此外,尽管您犯了小错误,但无论如何您都不会在控制台上看到结果,因为您缺少日志语句:

System.out.println("Your encrypted text was: ");
for (int i = 0; i < encryptedTextArray.size(); i++) {
encryptedString += encryptedTextArray.get(i);
}
System.out.println(encryptedString); // output your result

最新更新