Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Encrypting text 1

Status
Not open for further replies.

chris921

Technical User
Mar 9, 2004
82
GB
For some reason this piece of code will only encrypt one letter and wont loop back.

Can someone suggest a way around this?

There is another file that calls this method, there is no problem with that file.

Code:
public class CaesarCipher {

    private int key;

    public CaesarCipher( int inKey ) {
        // Initialise key
		key = inKey;
    }

    public String encrypt( String s ) {
        // Encrypt the argument a character at a time & return the result

		
		for (int i = 0; i<s.length(); i++){
			char letter = s.charAt(i);
			char newLetter = decrypt(letter);
			char [] data = {newLetter};
			String end = new String( data );
			return(end);
    }
return(s);
}

    public String decrypt( String s ) {
        // Decrypt the argument a character at a time & return the result

		for (int i = 0; i<s.length(); i++){
			char letter = s.charAt(i);
			char newLetter = decrypt(letter);
			char [] data = {newLetter};
			String end = new String( data );
			return(end);
		}
	return(s);
    }

    private char encrypt( char c ) {
        // Encrypt the argument & return the result
        if ((char)(c + key)>90 && (char)(c + key) < 97){
        	return (char)(c + key - 26);
		}else
		if ((char)(c + key)>123){
			return (char)(c + key - 26);
		}
		return (char)(c + key);
    }

    private char decrypt( char c ) {
        // Decrypt the argument & return the result
    	if ((char)(c - key)>90 && (char)(c - key) < 97){
		    return (char)(c - key + 26);
		}else
		if ((char)(c - key)<65){
			return (char)(c - key + 26);
		}
		return (char)(c - key);
    }
}
 
your code will always return the first character of the string.

char [] data = {newLetter}; <--- always an char array of 1
String end = new String( data ); <-- always a string of 1 char
return(end); <---- always return at the first loop.

You code should be somthing like:

Code:
    public String encrypt( String s ) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i<s.length(); i++){
            sb.append(encrypt(s.charAt(i));
        }
        return(sb.toString());
    }

    public String decrypt( String s ) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i<s.length(); i++){
            sb.append(decrypt(s.charAt(i));
        }
        return(sb.toString());
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top