next up previous
Next: The class EncryptedText: example Up: Unit 06 Previous: The class EncryptedText: public

The class EncryptedText: realization of the methods

We concentrate now on the single methods and realize their bodies. To do so, we make use of two auxiliary methods, encode() and decode(), analogous to the methods for encoding and decoding text according to a given key that we have already seen.

public class EncryptedText {
  // representation of the objects of the class
  private int key;
  private String text;

  // constructor
  public EncryptedText(String nonEncryptedText) {
    key = 0;
    text = nonEncryptedText;
  }
  public EncryptedText(String nonEncryptedText, int key) {
    this.key = key;
    text = encode(nonEncryptedText,key);
  }

  // altri metodi pubblici
  public String getEncryptedText() {
    return text;
  }
  public String getDecryptedText(int key) {
    if (key == this.key)
      return decode(text, key);
    else return null;
  }
  public boolean isKey(int candidateKey) {
    return candidateKey == key;
  }
  public void setKey(int key, int newKey) {
    if (key == this.key) {
      this.key = newKey;
      text = encode(decode(text,key),newKey);
    }
  }

  // auxiliary methods
  private static String encode(String text, int key) {
    String resText;
    char c;
    int ci;
    resText = "";
    for (int i = 0; i < text.length(); i++) {
      c = text.charAt(i);
      ci = (int)c;
      ci = ci + key;
          c = (char)ci;
      resText = resText + String.valueOf(c);
    }
    return resText;
  }
  private static String decode(String text, int key) {
    String resText;
    char c;
    int ci;
    resText = "";
    for (int i = 0; i < text.length(); i++) {
      c = text.charAt(i);
      ci = (int)c;
      ci = ci - key;
      c = (char)ci;
      resText = resText + String.valueOf(c);
    }
    return resText;
  }
}


next up previous
Next: The class EncryptedText: example Up: Unit 06 Previous: The class EncryptedText: public