當前,我正在嘗試在我創建的項目中執行凱撒密碼。但是,當我嘗試將字符串傳遞給處理它的實例時,它似乎根本無法處理它。 (現在我忽略空格和標點符號)。Java新手試圖將字符串傳遞給實例java
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
這與String的不變性無關。這都是因爲通過價值 –
@AdrianShum你是對的。 –