Search code examples
javaencryptioncaesar-cipher

Get result from for loop and add it to another variable for every iteration


I have an assignment where I am supposed to write a program that can encrypt and decrypt a word the user enters, using an "encryption key" they enter. What I want to do is to check the value of every letter in the key the enter, compared to the alphabet (eg: a = 1, b = 2, c = 3) and then add the value of the letters, which will then be used to shift the characters in the word they assign. This is the code I have for my assignment so far:

    /* Validity Check from http://stackoverflow.com/questions/33965542/password-check-program-checking-capitals-lowercase-letters-digit-and-special
 * 
 * 
 * 
 * 
 */
import java.util.*;
public class SecretDecoderFinal
{
  public static void main (String [] args)
  {
    optInput();

  }

  public static int optInput()
  {
    int opt = 0;
    do {
      String word = "";
      String key = "";
      System.out.println("Welcome to Seegson Security secure transmission terminal");
      System.out.println("");
      System.out.println("Enter an option for the terminal");
      System.out.println("(1) to encrypt a word");
      System.out.println("(2) to decrypt a word");
      System.out.println("(0) to exit the terminal");
      opt = In.getInt();
      System.out.println("You selected: Option " +opt);
      System.out.println("");
      switch(opt)
      {
        case 1:
          encryptWord(word, key);
          break;
        case 2:
          decryptWord(word, key);
          break;
        case 0:
          System.out.println("Thank you for using the encryption/decryption program");
          break;
        default:
          System.err.println("Invalid option. Select 1 for encryption, 2 for decryption, or 0 to exit");
          System.out.println("");
          break;
      }
    }while (!isExit(opt));

    return opt;

  }

  public static String keyInput(String key)
  {


    do
    {
      System.out.println("Enter the key you want for encryption/decryption");
      key = In.getString();
      System.out.println("Your key is: " +key);
      System.out.println("");

    }while (!isValid(key));
    //printEncrypted(key);

    return key;

  }

  public static String wordInput(String word)
  {

    do
    {
      System.out.println("Enter the word you want decrypted/encrypted");
      word = In.getString();
      System.out.println("You entered: " +word);
      System.out.println("");
    } while (!isValid(word));
    //printEncrypted(word);
    return word;

  }

  public static void encryptWord(String word, String key)
  {
   // String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";

    wordInput(word);
    keyInput(key);
    System.out.println("The word from the encryptWord metod " +word);
    printEncrypted(word, key);

  }

  public static void decryptWord(String w, String k)
  {
    String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    wordInput(w);
    keyInput(k);

  }

This part of code is from my friend

public static String printEncrypted(String word, String key)
  {
    System.out.println("This is the word from the printEncrypted method: " +word);

    int shift = 0;

    //Uses the key length to determine how much the alphabet will shift
    for (int x = 0; x < key.length(); x++) 

      shift += key.charAt(x) - 96; 
    shift = shift % 26;


    //Creates an array to perform the shift
    char [] y = word.toCharArray(); 

    for (int x = 0; x < y.length; x++) 
      //Uses the shift to shift the alphabet to decrypt the word.
      for (int d = 0; d < shift; d++)

      if (y[x] == 'z') 

      y[x] = 'a';

    else {
      y[x]--;
    } 
    String newWord = new String(y);
    System.out.println("Encrypted is " +newWord);
    return newWord;


  }

  public static boolean isValid (String s)
  {
    String strSpecialChars="!@#$%&*()_+=-|<>?{}[]~";
    //String alphabet2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    boolean upCase = false;
    boolean isDigit = false;
    boolean spChar = false;

    if (s.matches(".+[A-Z].+")){
      upCase = true;
    }

    if (s.matches(".+[1-9].+")){
      isDigit = true;
    }

    if (strSpecialChars.contains(s)){
      spChar = true;
    }


    if (upCase|| isDigit || spChar)

    {
      System.err.println("The string cannot contain capital letters, special characters or numbers. Try again.");
      System.out.println("");
      return false;
    }
    else 
    {
      return true;
    }

  }


  public static boolean isExit (int option)
  {
    if (option == 0)
    {

      return true;
    }
    else
    {
      return false; 
    }
  } 

}

And this is what I am trying to do for my character shift:

public class LetterTester
{
  public static void main (String []args)
  {

    String input="craig";
    final String alphabet="abcdefghijklmnopqrstvwxyz";
    int finalValue = 0;
    int[] numbers;
    for(int i=0;i<input.length();i++){

      finalValue=(alphabet.indexOf(input.charAt(i))+1);
      System.out.print(finalValue);

    }

  }
}

However, I don't know how to create a variable and get my for loop to add its output to the variable every time it runs. The LetterTester is just for testing. In my actual assignment, the input will be taken from another method, and then tested. So, for example, if the key is "abc", it will have the value of each of its letter determined, so a = 1, b = 2, c = 3. Then I want it to be added together into a variable which I can use. So the variable should equal 6 when the calculations for the input are finished.

Also, not sure if I should make a second question for this, but in the code for my assignment, I am not able to pass in the value of my word and key inputs from their respective methods (keyInput and wordInput) to a method called encryptWord, it shows the word as blank when I try to test it from the encryptWord method.

If anyone is wondering what I have done for the input, I'm using the In class, which I got from here: http://www.ecf.utoronto.ca/~jcarter/

My instructor has taught the class from the beginning by teaching us to use the In class so far.


Solution

  • There is simply too much going on in the OP's question to fully answer. The following code is a guideline to the solution space.

    • Gather the input for the word and key separately from each other and any other operation. The method getWord() and getKey would need to use the In class as noted by the OP. The point here is that the methods do not need any parameters, have a return, and only gather the information (thus separating input from processing).
    • The encryptWord(String, String) method takes the gathered input and transforms it in some fashion, returning the transformation. It should not do any output (again, separate I/O from processing). I did not attempt to replicate the encryption algorithm.
    • The decryptWord(String, String) method also takes collected input and transforms it following an algorithm. No attempt here was made to implement anything, but essentially it is the inverse of the encryption.
    • Really not everything should be static, but it follows the OP's approach.
    • The isValid(String) appears to be limiting to only lower case letters. Obviously it can be adjusted if that assumption is incorrect.

      //  
      // is valid checks to see if only lower case characters  
      //  
      private static boolean isValid(final String chkWord)
      {
        // returns true only if the match is lower case a-z
        return chkWord.matches("^[a-z]+$");
      }
      
      private static String encryptWord(String word, String key)
      {
        // TODO: implement the encryption algorithm;
        //   The algorithm would use the key to do the encryption;
        // here will just add to character as quick example
        char[] wordChars = word.toCharArray();
      
        for (int i = 0; i < wordChars.length; ++i) {
            char c = wordChars[i];
            if (c >= 'a' && c <= 'm') { c += 13; }
            else if (c >= 'n' && c <= 'z') { c -= 13; }
            wordChars[i] = c;
        }
      
        return new String(wordChars);
      }
      
      private static String decryptWord(String word, String key)
      {
        // TODO: implement the decryption algorithm
        return "NEED TO IMPLEMENT";
      }
      
      private static String getWord()
      { 
        // the word should be gathered from the user in some fashion
        // using the In class that is provided
        return "helloworld"; 
      }
      
      private static String getKey()
      {
        // the key should be gathered from the user in some fashion
        // using the In class that is provided
        return "doit";
      }
      
      public static void main(String[] args)
      {
        final String word = getWord();
        final String key = getKey();
      
        boolean validWord = isValid(word);
        System.out.printf("Is valid [%s]: %b%n", word, validWord);
      
        if (! validWord) {
          System.err.println("Not a good word!");
          return;
        }
      
        String encrypted = encryptWord(word, key);
        System.out.printf("Encrypted %s: %s%n", word, encrypted);
      
        String decrypted = decryptWord(word, key);
        System.out.printf("Encrypted %s: %s%n", word, decrypted);
      
      }
      

    Quick test of isValid():

    Is valid [Hello]: false
    Is valid [hello]: true
    Is valid [specialchar*]: false