我正在尝试创建一个Caesar Shift密码加密和解密程序。我需要它能够接受用户输入,直到用户希望退出(q),但我最终只是重复一切。
这是我的班级
import java.util.Scanner;
public class CaesarShift
{
//initialize private string for the alphabet
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//public encryption code
public String encryptionMethod(String normText, int caesarShift)
{
normText = normText.toLowerCase();
String cipherText = "";
for (int a = 0; a < normText.length(); a++)
{
int charP = ALPHABET.indexOf(normText.charAt(a));
int shiftValue = (caesarShift + charP) % 26;
char replaceValue = this.ALPHABET.charAt(shiftValue);
cipherText += replaceValue;
}
return cipherText;
}
public String decryptionMethod(String cipherText,int caesarShift)
{
cipherText = cipherText.toLowerCase();
String normText = "";
for (int a = 0; a < cipherText.length(); a++)
{
int charP = this.ALPHABET.indexOf(cipherText.charAt(a));
int keyValue = (charP - caesarShift) % 26;
if(keyValue < 0)
{
keyValue = this.ALPHABET.length() + keyValue;
}
char replaceValue = this.ALPHABET.charAt(keyValue);
normText += replaceValue;
}
return normText;
}
}
这是我的测试器方法,我尝试实例化while循环
import java.util.Scanner;
public class CaesarShiftTester
{
public static void main(String args[])
{
//import of the scanner method to ask the user for the input they would like
Scanner in = new Scanner(System.in);
System.out.println("What is the text you would like to do something with?(q to quit)");
String normText = in.nextLine();
System.out.println("What is the Caesar Shift Value?");
int caesarShift = in.nextInt();
//new declaration of the CaesarShift class to report back to easily
CaesarShift shift = new CaesarShift();
//declare the while method loop
while(normText != "q")
{
//decalre the need properties for the encryption
String cipherText = shift.encryptionMethod(normText, caesarShift);
System.out.println("Your normal text is: " + normText);
System.out.println("Your text after encryption is: " + cipherText);
String cnormText = shift.decryptionMethod(cipherText, caesarShift);
System.out.println("Your encrypted text is: " + cipherText);
System.out.println("Your decrypte text is: " + cnormText);
}
}
}
答案 0 :(得分:3)
while(normText != "q")
这是你的问题。 ==
和!=
运算符用于比较引用,而不是值。
将其更改为:
while(!q.equals(normText))
答案 1 :(得分:3)
您永远不会在while
循环内提示任何用户输入,因此它永远在旋转。在循环中添加用户输入检查:
while (!normText.equals("q")) {
String cipherText = shift.encryptionMethod(normText, caesarShift);
System.out.println("Your normal text is: " + normText);
System.out.println("Your text after encryption is: " + cipherText);
String cnormText = shift.decryptionMethod(cipherText, caesarShift);
System.out.println("Your encrypted text is: " + cipherText);
System.out.println("Your decrypte text is: " + cnormText);
System.out.println("What is the text you would like to do something with?(q to quit)");
normText = in.nextLine();
}
正如@Stultuske在他的回答中提到的那样,你也试图在使用String
内部使用!=
运算符比较String.equals()
的值。但是不检查while
循环内的用户输入是一个更大的问题。