简体   繁体   English

C#:使用输入控制台优化错误预防

[英]C#: Optimizing error prevention with the input console

I've just started learning C# using Rob Miles' C# Programming Yellow Book and some related lab exercises from his website. 我刚刚开始使用Rob Miles的C#编程黄皮书和他网站上的一些相关实验练习来学习C#。 I did one of them and produced a solution that works...(there's not one provided). 我做了其中一项,并提出了一种可行的解决方案...(没有提供)。 I wanted it to not crash if the user inputs nonsensical answers or a string that can't be converted into an integer(I Googled this and found the TryParse method. The textbook briefly taught the try/catch method, but that didn't seem useful for a user interface, ie to let the program continue after a bad input). 我希望它在用户输入无意义的答案或无法转换为整数的字符串时不会崩溃(我对此进行了Google搜索,找到了TryParse方法。教科书简要地介绍了try / catch方法,但似乎没有对于用户界面很有用,即让程序在输入错误后继续运行)。 I also set it up so that, in one of these cases, it sends out an alternate message. 我还进行了设置,以便在其中一种情况下,它发出备用消息。 I've ended up with a somewhat long code... a do/while within a do/while and a do/while within a while. 我最终得到了一个较长的代码...一个do / while内执行一次do / while,以及在一段时间内执行do / while。 If you have any tips for streamlining this, I'd be much obliged. 如果您有任何简化技巧,我将非常有义务。

Best, Elliot 最好,艾略特

using System;
using System.IO;

static class Cinema
{
    static void Main()
    {
    int[] selection = new int[] //array for the age requirements of each film
        {
        15, 15, 12, 18, 0
        };
    string filmNumberText; //console input for the film number 
    int filmNumber; //input string parsed as integer 
    string ageText; //console input for age
    int age; //parsed age string
    int ageLimit; //age requirement for selected film

    Console.Write("Welcome to our Multiplex.\n\n");
    Console.WriteLine(@"We are presently showing:
    1. Rush (15) 
    2. How I Live Now (15)
    3. Thor: The Dark World (12A)
    4. Filth (18)
    5. Planes (U)");
    do  //loops as long as input is not between 1 and 5
    {
        do //loops as long as the input is not an integer
        {
            Console.Write("\nEnter the number of the film you wish to see: ");
            filmNumberText = Console.ReadLine();
        }
        while (int.TryParse(filmNumberText, out filmNumber) == false);
    } while (filmNumber < 1 || filmNumber > 5);

    filmNumber = filmNumber - 1; //changes input from 1-5 to 0-4
    ageLimit = selection[filmNumber]; //selects age requirement from array

     //loops as long as input is not an integer

        do
        {
            Console.Write("\nEnter your age: ");
        ageText = Console.ReadLine();
        } while (int.TryParse(ageText, out age) == false); // repeats if input is not an integer



    while (age < 0 || age > 125) //if integer is is too small or too large...
    {
        do
        {
            Console.Write("\nInvalid age. Please enter an age between 0 and 125: ");
            ageText = Console.ReadLine();
        } while (int.TryParse(ageText, out age) == false); //check again if input is an integer
    }
    if (age < ageLimit) //if too young for the given film
        {
            Console.WriteLine("\nAccess denied - you are too young");
        }
    else
        {
            Console.WriteLine("\nPlease call our office at 888-999-2928 to reserve tickets.");
        }

        }
}

I have tried to remove some do while loop from your code. 我试图从您的代码中删除一些do while循环。 is this what are you looking for? 这是你在找什么?

public static void Main()
{
    int[] selection = new int[] //array for the age requirements of each film
    {
    15, 15, 12, 18, 0
    };
    string filmNumberText; //console input for the film number 
    int filmNumber; //input string parsed as integer 
    string ageText; //console input for age
    int age; //parsed age string
    int ageLimit; //age requirement for selected film

    Console.Write("Welcome to our Multiplex.\n\n");
    Console.WriteLine(@"We are presently showing:
1. Rush (15) 
2. How I Live Now (15)
3. Thor: The Dark World (12A)
4. Filth (18)
5. Planes (U)");
    do  //loops as long as input is not between 1 and 5
    {

        Console.Write("\nEnter the number of the film you wish to see: ");
        filmNumberText = Console.ReadLine();
    } while (int.TryParse(filmNumberText, out filmNumber) == false || (filmNumber < 1 || filmNumber > 5));

    filmNumber = filmNumber - 1; //changes input from 1-5 to 0-4
    ageLimit = selection[filmNumber]; //selects age requirement from array

    //loops as long as input is not an integer

    do
    {
        Console.Write("\nPlease enter an age between 0 and 125:");
        ageText = Console.ReadLine();
    } while (int.TryParse(ageText, out age) == false || (age < 0 || age > 125)); //check again if input is an integer

    if (age < ageLimit) //if too young for the given film
    {
        Console.WriteLine("\nAccess denied - you are too young");
    }
    else
    {
        Console.WriteLine("\nPlease call our office at 888-999-2928 to reserve tickets.");
    }

    Console.Read();

}

you may consider the following refactoring: 您可以考虑以下重构:

  static class Cinema
    {
        static void Main()
        {
            string[] titles = new string[] {"Rush", "How I Live Now", "Thor: The Dark World", "Filth", "Planes" };//array for the age requirements of each film
            int[] selection = new int[] { 15, 15, 12, 18, 0 };//array for the age requirements of each film
            int filmNumber; //parsed film number string 
            int age; //parsed age string

            Console.WriteLine("Welcome to our Multiplex.\n\nWe are presently showing:");
            for (int i = 0; i < titles.Length; i++)
            {
                Console.WriteLine("{0}. {1} ({2})",i+1, titles[i],selection[i]);
            }


            filmNumber = GetIntNumber(1, 5, "\nEnter the number of the film you wish to see: ", "\nPlease enter a number between 1 and 5: ");

            //loops as long as input is not an integer

            age = GetIntNumber(0, 125, "\nEnter your age: ", "\nPlease enter an age between 0 and 125: ") - 1; 
            if (age < selection[filmNumber-1]) //if too young for the given film
            {
                Console.WriteLine("\nAccess denied - you are too young");
            }
            else
            {
                Console.WriteLine("\nPlease call our office at 888-999-2928 to reserve tickets.");
            }
            Console.ReadLine();

        }

        static int GetIntNumber(int min, int max, string prompt, string inputPrompt)
        {
            int number;

            Console.Write(prompt);
            do  //loops as long as input is not between 1 and 5
            {
                Console.Write(inputPrompt);
                while (!int.TryParse(Console.ReadLine(), out number)) //loops as long as the input is not an integer
                {
                    Console.Write("\nYou must enter an integer number!");
                } 
            } while (number < min || number >max);
            return number;
        }

edit to throw in Alternative 1 for GetInNumber() method prompts handling: 编辑以为GetInNumber()方法放入替代方法1会提示处理:

    static int GetInNumber(int min, int max, string prompt, string inputPrompt)
    {
        int number;

        Console.Write(prompt);
        do  //loops as long as input is not between 1 and 5
        {
            while (!int.TryParse(Console.ReadLine(), out number)) //loops as long as the input is not an integer
            {
                Console.Write("\nYou must enter an integer number!: ");
            }
            if (number < min || number > max) Console.Write(inputPrompt); //<--| write input prompt if number out of range
        } while (number < min || number > max);

        return number;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM