Help with Caeser Cypher

Hi all. I am completely stumped on the Caesar Cypher. I am very close, but keep getting an error and I can’t figure it out.

here is my code:
using System;

namespace CaesarCipher
{
class Program
{
static void Main(string args)
{
char alphabet = new char {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’};

  Console.Write("Input secret message: ");
 string message = Console.ReadLine();
  char[] secretMessage = message.ToCharArray();
  
  char[] encryptedMessage = new char[25];
  
  for (int i = 0; i < 26; i++)
  {
    char secretItem = secretMessage[i];
     int index = Array.IndexOf(alphabet, secretItem);
  int letterPosition = (index += 3 % 26);
    
    char encryptedLetter = alphabet[letterPosition];
   encryptedMessage[i] = encryptedLetter;
  }
  
  string superSecretMessage = String.Join("", encryptedMessage);
  
 
  
  
}

}
}

and the error message is a unhandled exception.

It will let me type in my secret message, but once I do i get the error.

I imagine your error message says more than that.

After replacing your ‘’ characters with quotes (please take care to keep your code intact in your post), running it looks like this for me:

$ mcs -debug CaesarCipher.cs
CaesarCipher.cs(27,10): warning CS0219: The variable `superSecretMessage' is assigned but its value is never used
Compilation succeeded - 1 warning(s)
$ mono --debug CaesarCipher.exe
Input secret message: aoeu

Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at CaesarCipher.Program.Main (System.String[] args) [0x0003c] in /tmp/derp/aetuh/CaesarCipher.cs:19 
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at CaesarCipher.Program.Main (System.String[] args) [0x0003c] in /tmp/derp/aetuh/CaesarCipher.cs:19 
3 Likes

Hello, @ruby4126738306. Welcome to the forum!

Your problem appears to be in this line. Re-check the hint from the lesson. A portion of what you have inside the parenthesis belongs on the outside. :wink:

P.S. I’d change += to just +. No need to change the value assigned to index. You just need to calculate the value to be assigned to letterPosition.

3 Likes