Hi there, I am on the 12th step of the Caesar Cipher project, but I keep on having this error printed on the screen after I enter my input:
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at CaesarCipher.Program.Main(String args) in /home/ccuser/workspace/csharp-caesar-cipher/Program.cs:line 26
I have looked over my code multiple times, and there doesn’t appear to be any noticeable problems with it, such as an incorrect indentation of any line of code. I have also struggled with whether to declare the variable I created on line 25 an int or a char, though neither declaration brings an end to the appearance of errors. Please examine my code below, I am open to advice on how to approach the issues I am facing:
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’};
// Ask for secret message:
Console.WriteLine("Enter a secret message: ");
string result = Console.ReadLine();
char[] secretMessage = result.ToCharArray();
char[] encryptedMessage = new char[secretMessage.Length];
// Encrypt letters in message:
for (int i = 0; i < secretMessage.Length; i++)
{
char positionMessage = secretMessage[i];
int positionAlphabet = Array.IndexOf(alphabet, positionMessage);
int valueThree = (positionAlphabet + 3) % alphabet.Length;
int newEncryptedCharacter = alphabet[positionAlphabet];
encryptedMessage[i] = alphabet[newEncryptedCharacter];
}
string readableMessage = String.Join("", encryptedMessage);
Console.WriteLine(readableMessage);
}
}
}