2012-10-24 76 views
1

當前,我正在嘗試在我創建的項目中執行凱撒密碼。但是,當我嘗試將字符串傳遞給處理它的實例時,它似乎根本無法處理它。 (現在我忽略空格和標點符號)。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 

回答

1

您的新encyrpted字符串是一個返回值。你傳遞給方法的字符串是不變的。嘗試例如

String encryption = cipher.encryptIt(phrase); 
JOptionPane.showMessageDialog(null, encryption); 
1

您需要再次將返回值分配給phrase

phrase=cipher.encryptIt(phrase); 
0

您必須改變phrase變量的值,該行

cipher.encryptIt(phrase); 

改變

phrase = cipher.encryptIt(phrase); 

這是因爲Java按值傳遞所有參數。這意味着,當您通過方法發送變量時,您不會發送實際引用,而是發送引用的副本。

+1

這與String的不變性無關。這都是因爲通過價值 –

+0

@AdrianShum你是對的。 –

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

相關問題