我正在尝试使用一个非常基本的程序(我稍后会添加)来对用户输入的文本执行凯撒转换。
我有很多工作,但当我试图打印出“加密”字符串时,它不起作用。我正在使用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的范围内。如果你在表中查找,你会发现a
和z
都没有,也不是A
到Z
的值。实际上,所有这些字符都是invisibe或空白。
以下示例演示了小写字符的正确用法:
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