0

Okay, so for a school project I am attempting to make a method that will take a file, use a caesar cipher to 'encrypt' it, and then output the new encrypted word to an output file, reading in all the words of the file to leave us with a separate encrypted file.

The problem I'm running into is I get a

"Unexpected type. Required: variable. Found: value" error

whenever I try to replace the character with the new one.

Here's my encryption method, so hopefully that will be enough to find the problem.

public static void encrypt(File inputFile, int key) throws FileNotFoundException
{
    char[] alpha = new char[26];
    for(char ch = 'a'; ch <= 'z'; ch++)
    {
        int i = 0;
        alpha[i] = ch;
        i++;
    }
    Scanner in = new Scanner(inputFile);
    while(in.hasNext())
    {   
        String word = in.next();
        word = word.toLowerCase();
        for(int i = 0; i < word.length(); i++)
        {
            for(int j = 0; j < alpha.length; j++)
            {
                if(word.charAt(i) == alpha[j])
                {
                    word.charAt(i) = alpha[j + key];       
                }
            } 
        }

    }  
}
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48

1 Answers1

0

As Strings are immutable you can not do

word.charAt(i) = alpha[j + key];

Consider using a StringBuilder instead, like

    StringBuilder buf = new StringBuilder ();
    for(int i = 0; i < word.length(); i++)
    {
        for(int j = 0; j < alpha.length; j++)
        {
            if(word.charAt(i) == alpha[j])
            {
                buf.append(alpha[j + key]);
            }
            else {
                buf.append (word[i]); // ??
            }
        }
    }

    // do something with buf ??
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • Thanks, that seems to have solved that problem. Just curious, how would you print this out to a file now? I need to print one word at a time obviously, but how would I go about doing that without overwritting the save file each time. – Redfox2045 Nov 11 '16 at 20:04
  • @Redfox2045 I am glad it helps. Please consider to upvote and/or accept this answer. – Scary Wombat Nov 14 '16 at 00:37
  • @Redfox2045 As per your other question, please review http://stackoverflow.com/questions/8563294/modifying-existing-file-content-in-java – Scary Wombat Nov 14 '16 at 00:38