1

目前,我正在尝试在我正在创建的项目中执行凯撒密码。但是,当我尝试将字符串传递给处理它的实例时,它似乎根本没有处理它。(现在我忽略了空格和标点符号)。

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 
4

4 回答 4

1

您需要phrase再次分配返回值。

phrase=cipher.encryptIt(phrase);
于 2012-10-24T03:19:21.983 回答
1

您的新加密字符串是一个返回值。您传递给该方法的字符串保持不变。例如尝试

String encryption = cipher.encryptIt(phrase); 
JOptionPane.showMessageDialog(null, encryption ); 
于 2012-10-24T03:21:47.430 回答
0

您必须更改此行

cipher.encryptIt(phrase);

phrase = cipher.encryptIt(phrase);

为了改变phrase变量的值。

这是因为 Java 通过值传递所有参数。这意味着,当您通过方法发送变量时,您发送的不是实际引用,而是引用的副本。

于 2012-10-24T03:20:03.547 回答
0

您应该知道的一件事:方法参数在 Java 中是按值传递的

简单来说:

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()

于 2012-10-24T03:38:40.987 回答