using System;
namespace CaesarCipher
{
class Program
{
public static class Globals
//This makes it so the alphabet array can be accessed in multiple methods so it doesn't need to be defined each time.
{
public static 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'};
}
static void Encrypt()
{
Console.WriteLine("What secrets ye' hold?");
string rawMessage = Console.ReadLine().ToLower();
//This makes it so your user input is automatically percieved in lower case.
char[] secretMessage = rawMessage.ToCharArray();
char[] encryptedMessage = new char[secretMessage.Length];
for (int i = 0; i < secretMessage.Length; i++)
{
char fehu = secretMessage[i];
bool alpha = Char.IsLetter(fehu);
//This checks if the lettter being checked is a letter or not.
if (alpha == true)
//If it is a letter, the program runs normally.
{
int uruz = Array.IndexOf(Globals.alphabet, fehu);
int thurisaz = (uruz += 3) % Globals.alphabet.Length;
char ansuz = Globals.alphabet[thurisaz];
encryptedMessage[i] = ansuz;
}
else
//This leaves non-letters unaltered.
{
encryptedMessage[i] = secretMessage[i];
}
}
string transcription = String.Join("", encryptedMessage);
Console.WriteLine(transcription);
}
static void Decrypt()
//This is the same exact code as the encryption except for the greeting message and...
{
Console.WriteLine("What have you heard?");
string rawMessage = Console.ReadLine().ToLower();
char[] secretMessage = rawMessage.ToCharArray();
char[] encryptedMessage = new char[secretMessage.Length];
for (int i = 0; i < secretMessage.Length; i++)
{
char fehu = secretMessage[i];
bool alpha = Char.IsLetter(fehu);
if (alpha == true)
{
int uruz = Array.IndexOf(Globals.alphabet, fehu);
int thurisaz = (uruz -= 3) % Globals.alphabet.Length;
//The second difference, where you subtract 3 instead of adding it.
char ansuz = Globals.alphabet[thurisaz];
encryptedMessage[i] = ansuz;
}
else
{
encryptedMessage[i] = secretMessage[i];
}
}
string transcription = String.Join("", encryptedMessage);
Console.WriteLine(transcription);
}
static void Main(string[] args)
{
string beta = "";
// Defining the variable for whether you want something encrypted or decrypted.
Console.WriteLine("Do you speak, or do you listen?");
// Lets the user decide if they're encrypting or decrypting.
beta = Console.ReadLine().ToLower();
if (beta == "speak")
{
Encrypt();
}
else if (beta == "listen")
{
Decrypt();
}
}
}
}
Hi, I tested out your Decrypt method and running into an issue. There’s an error with int thurisaz = (uruz -= 3) % Globals.alphabet.Length;
because subtracting 3 results in a negative number in the index even with modulo. Typing in the letters a, b, or c will throw an unhandled exception error because of their positions in the alphabet array and they do not wrap around like the encryption method.