我正在尝试开发一个非常基本的程序(稍后将添加到该程序上)以对用户输入的文本执行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
任何建议或意见,我们将不胜感激。我没有找到有关此特定问题的任何示例。谢谢。
答案 0 :(得分:0)
请密切注意Ascii表和您的表情
newCurrValue = ((currValue-3) % 26);
您要从当前值中减去3,然后采用mod 26,这可以确保您得出的结果在0到26的范围内。如果您在表中向上查找,则不会发现{ {1}}至a
或z
至A
的值。实际上,所有这些字符都是无形的或空白的。
下面的示例演示了小写字符的正确用法:
Z
尽管有一些小错误,但由于缺少日志语句,您还是不会在控制台上看到结果:
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'