1

現在、作成中のプロジェクトで 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 
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

知っておくべき重要なことの 1 つは、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 に答える