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];       
                }
            } 
        }

    }  
}

1 Answer 1

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 ??
Sign up to request clarification or add additional context in comments.

3 Comments

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 I am glad it helps. Please consider to upvote and/or accept this answer.
@Redfox2045 As per your other question, please review stackoverflow.com/questions/8563294/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.