-1

I am making a program that encrypts a string by increasing the value for each character by 5. Ex) A=F, B=G etc. Here is what I have come up with so far:

public class CharArray 
{
    public static void main(String[] args) 
    {   
        String str = "This sentence will be encrypted"; 

        char[] charArray = str.toCharArray(); 

        int pos=0; 

        while (pos<str.length())
        {
            char x = (charArray[pos]); 
            System.out.print((x+5) + " "); 
            //System.out.print(charArray[x]); This causes an exception error
            pos++;
        }


    }
}

But the output for this is:

89 109 110 120 37 120 106 115 121 106 115 104 106 37 124 110 113 113 37 103 106 37 106 115 104 119 126 117 121 106 105 
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 2
    cast to a char when you add 5 to it and no need for the `+" "` So something like this: `(char)(x+5)` – 3kings Nov 02 '15 at 05:47
  • Suggestions: for encryption use proper encryption methods, for questions on SO please provide [MCVE] (with emphasis on *minimal*) along with expected output/exact errors. – Alexei Levenkov Nov 02 '15 at 05:48
  • 2
    I assume this is for a class or self learning experience? You shouldn't use this "encryption" to protect any actually valuable data, it's far too weak. This algorithm is known as a [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher), and it's simple enough that humans can crack it in minutes, even without computer help, just by doing frequency analysis on the ciphertext. – Daniel Pryden Nov 02 '15 at 05:51
  • And btw, what do you want Z to be? `_`, `E`, something else? – yshavit Nov 02 '15 at 05:52
  • 2
    Possible duplicate of [How do I increment a variable to the next or previous letter in the alphabet in Java?](http://stackoverflow.com/questions/2899301/how-do-i-increment-a-variable-to-the-next-or-previous-letter-in-the-alphabet-in) – Alexei Levenkov Nov 02 '15 at 05:54
  • No it's just for a class, not to actually protect data. And I would z to be become E so the alphabet restarts. Sorry I forgot to mention that. – Thomas Alain Nov 02 '15 at 06:01

1 Answers1

3

Do not forget to cast. When doing an arithmetic operation, your char is implicitely casted into an int so you'll have to explicitely cast it back


Solution

System.out.println((char)(x+5));
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89