代码可以很好地编译,但最终不会打印任何内容。我是一个编程新手,已经在这上面工作了几个小时了,现在我在一堵墙上。
代码如下:
import java.util.Scanner;
public class caesartwo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String originalText;
int shiftValue;
//encryption
System.out.println("What text would you like to encrypt?");
originalText=keyboard.nextLine();
//shift value
System.out.print("\nWhat is the shift value? ");
shiftValue=keyboard.nextInt();
//encrypted string
String encryptedText=encrypt(originalText,shiftValue);
//print result
System.out.println("\nThe encrypted text is:\n" + encryptedText);
}
public static String rotate(String userString, int shiftValue) {
String convertedText = "";
for(int i = 0; i < userString.length(); i++){
char lowerLetter = userString.charAt(i);
//uppercase conversion
char upperLetter = Character.toUpperCase(lowerLetter);
int charNumber = upperLetter;
//shift and wrap
int rotateShift = (charNumber + shiftValue) % 26;
char shiftLetter = (char) rotateShift;
//shifted chars
convertedText += shiftLetter;
}
return convertedText;
}
public static String encrypt(String userString, int shiftValue) {
String encryptedString = rotate(userString , shiftValue);
return encryptedString;
}
}现在我不得不写更多的单词,因为我有太多的代码文本等等。
发布于 2014-01-28 12:05:10
您的rotate()方法中的变量有一些模糊。您应该提取它们并使其成为实例变量,而不是让循环的每个迭代创建新的变量。您可以更简单地完成此操作。将您的rotate方法替换为以下内容:
public static String rotate(String userString, int shiftValue) {
String convertedText = "";
int offset = shiftValue % 26 + 26;
int j;
for(int i = 0; i < userString.length(); i++){
j = (userString.charAt(i) - 'a' +offset) % 26;
convertedText += (char) (j+'a');
}
return convertedText;
}测试了它,它现在输出了一个值。从这里劫持了算法:http://rosettacode.org/wiki/Caesar_cipher#Java
发布于 2014-01-28 12:11:25
你的问题在这里。
char shiftLetter = (char) rotateShift;当我调试代码时,shiftletter不会被赋值。学会调试你的代码,你就能很快找到一条令人不快的语句。
发布于 2014-01-28 12:18:09
看一下rotateShift = (charNumber + shiftValue) % 26;这一行。我知道你在尝试包装ASCII值,这样如果你将“Z”移一,你就会得到“A”。然而,在ASCII表中,'A‘从65开始。将(charNumber + shiftValue)修改为26,则答案只能是介于0和25之间(包括0和25)的数字。如果您查看ASCII表,0-25都是特殊字符,不能打印,就像NULL字符和回车符一样。为了确保想要的结果,我建议将(charNumber + shiftValue) % 26加到65,这样你就可以从'A‘开始,而不会超过'Z’。
https://stackoverflow.com/questions/21396495
复制相似问题