不允许使用其他选项

时间:2019-01-06 22:26:43

标签: c# type-conversion coding-style

我遇到了一个小问题。我创建了一个程序,用户必须选择5个选项(1.输入数字2.显示最小3.显示最大4.显示所有数字5退出。)  所有选项均有效。问题是,当用户选择选项时,如果按任何字母都会给我错误。我希望如果用户按任何字母或任何符号作为警告消息,例如“输入的未知选项值”,然后重试。我想是关于转换或类似的东西,但我找不到问题所在。 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assignmen2014_15
{
    class Program
    {
    const int MAXNUMBERS = 3;
        static void Main(string[] args)
        {
        int[] theNumbers = new int[MAXNUMBERS];
        int chosenOption = 0;
        bool quit = false;

        InitialiseNumbers(theNumbers);
        while (quit == false)
            {
            DisplayHeader();
            DisplayMenu();
            chosenOption = ReadNumber("Please choose an option: ");
            quit = ProcessMenu(chosenOption, theNumbers);
            Console.Clear();
            }
        }
        static void InitialiseNumbers(int[] numbers)
        {
            for (int index = 0; index < MAXNUMBERS; index++)
            {
            numbers[index] = 0;
            }
        }
        static void DisplayHeader()
        {
        WriteText("*******************************************************************************", 0, 0); // Top left hand corner of screen is x = 0, y = 0;
        WriteText("* This application is designed to allow you to choose numbers *", 0, 1); // Next line down is x = 0, y = 1, etc WriteText("* and finds the biggest and the smallest value *", 0, 2);
        WriteText("*******************************************************************************", 0, 3);
        }
        static void DisplayMenu()
        {
            WriteText("Select an option", 20, 8); // Display menu at at x = 20, y = 8
            WriteText("1. Enter the numbers", 20, 9);
            WriteText("2. Find the smallest", 20, 10);
            WriteText("3. Find the largest", 20, 11);
            WriteText("4. Display all numbers", 20, 12);
            WriteText("5. Quit", 20, 13);
        }
        static void WriteText(string text, int x, int y)
        {
            Console.CursorLeft = x;
            Console.CursorTop = y;
            Console.Write(text);
        }
        static int ReadNumber(string prompt)
        {
            string text;
            int number;
            WriteText(prompt, 20, 14);
            text = Console.ReadLine();
            number = int.Parse(text);
            ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
            return number;

        }
        static void ClearText(int x, int y, int length)
        {
            // Write space ' ' characters starting at x, y for 'length' times
            WriteText(new String(' ', length), x, y);
        }

        static void DisplayNumbers(int[] theNumbers)
        {
            Console.Write("Your numbers are: ");
            for (int i = 0; i < MAXNUMBERS; i++)
            {
                Console.WriteLine(theNumbers[i]);
            }

        }

        static bool ProcessMenu(int option, int[] numbers)
        {
            bool quit = false;

            switch (option)
            {
                case 1:
                    GetNumbers(numbers);
                    break;
                case 2:
                    WriteText(string.Format("The smallest value is {0}", FindSmallest(numbers)), 20, 15);
                    Console.ReadKey(); // Pause
                    break;
                case 3:
                    WriteText(string.Format("The largest value is {0}", FindLargest(numbers)), 20, 15);
                    Console.ReadKey(); // Pause
                    break;
                case 4:
                    DisplayNumbers(numbers);
                    Console.ReadKey();
                    break;
                case 5:
                    quit = IsQuitting();
                    break;
                default:
                    WriteText("Unknown option value entered", 20, 15);
                    Console.ReadKey(); // Pause 
                    break;
            }
            return quit;
        }
        static void GetNumbers(int[] numbers)
        {
            for (int index = 0; index < MAXNUMBERS; index++)
            {
                numbers[index] = ReadNumber("Enter number: ");
            }
        }
        static int FindSmallest(int[] numbers)
        {
            int smallest = numbers[0];
            for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
            {
                if (numbers[index + 1] < smallest)
                {
                    smallest = numbers[index + 1];
                }
            }
            return smallest;
        }
        static int FindLargest(int[] numbers)
        {
            int largest = numbers[0];
            for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
            {
                if (numbers[index + 1] > largest)
                {
                    largest = numbers[index + 1];
                }
            }
            return largest;
        }
        static bool IsQuitting()
        {
            string response;
            bool quit = false;
            WriteText("Do you really wish to quit? ", 20, 13);
            response = Console.ReadLine();
            if (response.Equals("Yes" , StringComparison.InvariantCultureIgnoreCase) || response.Equals("Y", StringComparison.InvariantCultureIgnoreCase))
            {
                quit = true;
            }
            return quit;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用Int32.TryParse(String, Int32)方法尝试将字符串解析为整数,并返回表示解析成功与否的布尔值。在您的情况下,如果解析失败,则可以从ReadNumber方法返回-1,该方法将调用您的切换情况的default:部分,并显示错误消息。否则,如果解析成功,则只需返回解析的数字,该数字将是您想要的数字之一,或者将调用default:操作。

以下是Microsoft documentation

中的示例
String[] values = { null, "160519", "9432.0", "16,667",
                      "   -322   ", "+4302", "(100);", "01FA" };
foreach (var value in values) 
{
   int number;

   bool success = Int32.TryParse(value, out number);
   if (success)
   {
      Console.WriteLine("Converted '{0}' to {1}.", value, number);         
   }
   else
   {
      Console.WriteLine("Attempted conversion of '{0}' failed.", 
                         value ?? "<null>");
   }
}

在您的特定示例中,您需要修改ReadNumber(string prompt)方法:

static int ReadNumber(string prompt)
{
    string text;
    int number;
    WriteText(prompt, 20, 14);
    text = Console.ReadLine();
    bool is_parsing_successful = Int32.TryParse(text, out number);
    ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
    if(is_parsing_successful){
        return number;
    } else {
        return -1;
    }
}