-2

How to allow the user to press enter and for it to show incorrect instead of showing an error. When in the program the user can press enter without entering info and the system crashes giving a System.FormatException error in which i have no idea how to fix. Any help will be greatly appreciated and i thank you for reading.

double price, discount, answer, disprice, fahr, celc, celc2, fahr2;
        char test, choice;
        double Merc, mars, nept, uran, jup, sat, pluto, moon, venus;
        do
        {
            Console.WriteLine("Choose from the following:");
            Console.WriteLine("A: Mecury ");
            Console.WriteLine("B: Venus ");
            Console.WriteLine("C: Mars ");
            Console.WriteLine("D: Jupitar");
            Console.WriteLine("E: Saturn ");
            Console.WriteLine("F: Uranus ");
            Console.WriteLine("G: Neptune ");
            Console.WriteLine("H: Pluto ");
            Console.WriteLine("I: Moon ");
            Console.WriteLine("Z: Help ");
            Console.WriteLine("Q: to quit the program");
            choice = char.Parse(Console.ReadLine());

            switch (choice)

2 Answers2

0

Instead of using char.Parse(), try char.TryParse():

....
Console.WriteLine("Q: to quit the program");
if (!char.TryParse(Console.ReadLine(), out choice)
{
    continue; // Assuming your do/while loop will just loop. Might need to modify the while condition
}

switch (choice)
...
itsme86
  • 19,266
  • 4
  • 41
  • 57
0

Parse will always throw if you pass it junk data.

You can catch it:

try
{
   choice = char.Parse(...);
}
catch (FormatException ex)
{
   //Display error
}

Or use TryParse which doesn't throw:

if (char.TryParse(..., out choice))
{
   //Value in choice
}
else
{
   //Parse Failed
}
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117