I have to write a "encryption" program for my C# intro class. I'm encountering 2 problems:
- When a negative is entered or it calculates a negative during the decryption process, it crashes. - it returns and unhandled exception error: System.FormatException: Input string was not in a correct format.
- The decryption should be the reverse of the encryption without using the original variable. How do you reverse a remainder calculation?
I know it's part of the do while loop that's the issue, I'm just not sure how to continue to prompt for a value if a negative is entered and if encountered during the decryption calculation to keep it from crashing. Any guidance would be much appreciated. Thanks for taking a look at it!
public class MainClass
{
public static void Main(string[] args)
{
int num = 0;
int dnum = 0;
do
{
Console.Write("Please enter a non-negative integer to encrypt: ");
num = Convert.ToInt32(Console.ReadLine());
string numstr = Convert.ToString(num);
string num1 = Convert.ToString(numstr.Substring(0, 1));
string num2 = Convert.ToString(numstr.Substring(1, 1));
string num3 = Convert.ToString(numstr.Substring(2, 1));
string num4 = Convert.ToString(numstr.Substring(3, 1));
int enum1 = ((Convert.ToInt32(num1) + 7) % 10);
int enum2 = ((Convert.ToInt32(num2) + 7) % 10);
int enum3 = ((Convert.ToInt32(num3) + 7) % 10);
int enum4 = ((Convert.ToInt32(num4) + 7) % 10);
Console.WriteLine("Encrypted Integer: {0:D4}", (1000 * enum3 + 100 * enum4 + 10 * enum1 + enum2));
Console.Write("Please enter a non-negative integer to decrypt: ");
dnum = Convert.ToInt32(Console.ReadLine());
string dnumstr = Convert.ToString(dnum);
string num1d = Convert.ToString(dnumstr.Substring(0, 1));
string num2d = Convert.ToString(dnumstr.Substring(1, 1));
string num3d = Convert.ToString(dnumstr.Substring(2, 1));
string num4d = Convert.ToString(dnumstr.Substring(3, 1));
int dnum1 = ((Convert.ToInt32(num1d) - 7) * 10);
int dnum2 = ((Convert.ToInt32(num2d) - 7) * 10);
int dnum3 = ((Convert.ToInt32(num3d) - 7) * 10);
int dnum4 = ((Convert.ToInt32(num4d) - 7) * 10);
Console.WriteLine("Decrypted Integer: {0:D4}", (1000 * dnum1 + 100 * dnum2 + 10 * dnum3 + dnum4));
} while (num > 0);
} // end Main
}// end class