目前,我正在尝试在我正在创建的项目中执行Caesar Cipher。但是,当我尝试将字符串传递给处理它的实例时,它似乎根本不处理它。 (现在我忽略了空格和标点符号)。
import javax.swing.*;
import java.text.*;
import java.util.*;
import java.lang.*;
public class Cipher {
private String phrase; // phrase that will be encrypted
private int shift; //number that shifts the letters
///////////////
//Constructor//
//////////////
public Cipher( int new_shift)
{
shift = new_shift;
}//end of cipher constructor
////////////
//Accessor//
////////////
public int askShift() {
return shift;
}//end of askShift accessor
////////////
//mutators//
////////////
public void changeShift (int newShift) {
shift = newShift;
}//end of changeShift mutator
/////////////
//instances//
/////////////
public String encryptIt(String message) {
char[] charArray = message.toCharArray(); //converts to a character array
//loop that performs the encryption
for (int count = 0; count < charArray.length; count++) {
int shiftNum = 2;
charArray[count] = (char)(((charArray[count] - 'a') + shiftNum) % 26 + 'a');
} // end of for loop
message = new String(charArray); //converts the array to a string
return message;
}//end of encrypt instance
//////////
///Main///
//////////
public static void main(String[] args) {
Cipher cipher = new Cipher(1); //cipher with a shift of one letter
String phrase = JOptionPane.showInputDialog(null, "Enter phrase to be messed with ");
cipher.encryptIt(phrase);
JOptionPane.showMessageDialog(null, phrase);
}//end of main function
} //end of cipher class
答案 0 :(得分:1)
您需要再次将返回值分配给phrase
。
phrase=cipher.encryptIt(phrase);
答案 1 :(得分:1)
您的新加密字符串是返回值。您传入方法的字符串不变。试试例子
String encryption = cipher.encryptIt(phrase);
JOptionPane.showMessageDialog(null, encryption );
答案 2 :(得分:0)
您必须更改此行
cipher.encryptIt(phrase);
到
phrase = cipher.encryptIt(phrase);
为了更改phrase
变量的值。
这是因为Java传递了所有参数的值。这意味着,当您通过方法发送变量时,您不会发送实际引用,而是发送引用的副本。
答案 3 :(得分:0)
您应该知道的一件主要事情:方法参数是Java中的pass-by-value
简而言之:
public void foo(Bar bar) {
bar = new Bar(999);
}
public void someMethod() {
Bar b = new Bar(1);
foo(b);
// b is still pointing to Bar(1)
}
因此,您的message = new String(charArray);
不会影响传递给encryptIt()