如何防止C#中输入无效导致崩溃?

时间:2010-03-03 00:39:06

标签: c# input crash

我编写的程序设置为仅接受正整数作为输入。如果用户输入了一个字母,那么它就会崩溃。负整数不会导致任何问题,尽管它对我的程序如何运作并不“有效”。

我想做的是:

  1. 防止程序因无效输入而崩溃。

  2. 如果输入无效,则显示错误消息

  3. 让程序在停止的地方继续,而不影响程序的其余部分。

  4. 此外,我的计划的一部分涉及分裂。有没有办法阻止用户输入全零?

    这是在C#

    我的代码:

    using System;
    

    使用System.Collections.Generic; 使用System.Linq; 使用System.Text;

    命名空间OverallCalculator {

    class Program
    {
        static void Main(string[] args)
        {
            bool shouldContinue;
    
    
            do
            {
    
    
    
    
                Console.WriteLine("Enter Striking Level: ");
    
                string striking = Console.ReadLine();
    
                Console.WriteLine("Enter Grappling Level: ");
    
                string grappling = Console.ReadLine();
    
                Console.WriteLine("Enter Submission Level: ");
    
                string submission = Console.ReadLine();
    
                Console.WriteLine("Enter Durability Level: ");
    
                string durability = Console.ReadLine();
    
                Console.WriteLine("Enter Technical Level: ");
    
                string technical = Console.ReadLine();
    
                Console.WriteLine("Enter Speed Level: ");
    
                string speed = Console.ReadLine();
    
                Console.WriteLine("Enter Hardcore Level: ");
    
                string hardcore = Console.ReadLine();
    
                Console.WriteLine("Enter Charisma Level: ");
    
                string charisma = Console.ReadLine();
    
    
    
    
                int gra = Convert.ToInt32(grappling);
                int str = Convert.ToInt32(striking);
                int dur = Convert.ToInt32(durability);
                int spd = Convert.ToInt32(speed);
                int tec = Convert.ToInt32(technical);
                int hdc = Convert.ToInt32(hardcore);
                int cha = Convert.ToInt32(charisma);
                int sub = Convert.ToInt32(submission);
    
                int total = str + gra + sub + dur + tec + spd + cha + hdc;
    
    
                int overall = total / 8 + 8;
    
    
    
    
                Console.WriteLine("The Overall is " + overall);
                Console.WriteLine("Do you wish to continue? y/n? ");
    
    
    
                if (Console.ReadLine() == "y")
                {
                    shouldContinue = true;
    
    
                }
                else break;
    
    
            } while (shouldContinue == true);
        }
    }
    

    }

5 个答案:

答案 0 :(得分:3)

int value = 0;
if (!int.TryParse(input, out value))
{
    MessageBox.Show("Oops");
} else {
    // use the value in the variable "value".
}

答案 1 :(得分:2)

static void Main(string[] args)
{
        bool validInput = false;
        string inputString;
        UInt32 validPositiveInteger = 0;
        while (!validInput)
        {
            Console.WriteLine("Please enter a positive 32 bit integer:");
            inputString = Console.ReadLine();
            if (!UInt32.TryParse(inputString, out validPositiveInteger))
            {
                Console.WriteLine("Input was not a positive integer.");
            }
            else if (validPositiveInteger.Equals(0))
            {
                Console.WriteLine("You cannot enter zero.");
            }
            else
            {                   

                validInput = true;
                //Or you could just break
                //break;
            }


        }

        Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}

答案 2 :(得分:1)

你走了:

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

namespace OverallCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            bool shouldContinue = true;

            while (shouldContinue)
            {
                int strikingLevel = GetValue("Enter Striking Level: ");
                int grapplingLevel = GetValue("Enter Grappling Level: ");
                int submissionLevel = GetValue("Enter Submission Level: ");
                int durabilityLevel = GetValue("Enter Durability Level: ");
                int technicalLevel = GetValue("Enter Technical Level: ");
                int speedLevel = GetValue("Enter Speed Level: ");
                int hardcoreLevel = GetValue("Enter Hardcore Level: ");
                int charismaLevel = GetValue("Enter Charisma Level: ");

                int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
                    technicalLevel + speedLevel + charismaLevel + hardcoreLevel;

                int overall = total / 8 + 8;

                Console.WriteLine("\nThe Overall is {0}.", overall);
                while (true)
                {
                    Console.WriteLine("Do you wish to continue? y/n? ");
                    string response = Console.ReadLine();
                    if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
                        response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
                    {
                        shouldContinue = true;
                        break;
                    }
                    else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
                        response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
                    {
                        shouldContinue = false;
                        break;
                    }
                }
            } 
        }

        private static int GetValue(string prompt)
        {
            while (true)
            {
                Console.WriteLine(prompt);
                string input = Console.ReadLine();
                int value;
                if (int.TryParse(input, out value))
                {
                    if (value <= 0)
                        Console.WriteLine("Please enter a positive number.");
                    else
                        return value;
                }
                else
                {
                    Console.WriteLine("Please enter a number.");
                }
            }
        }
    }
}

答案 3 :(得分:0)

是...在进行任何计算之前,您需要验证要使用的数据。如果任何数据不正确,则会显示一个消息框,详细说明错误并将焦点返回到表单,以便用户可以修复错误。根据需要重复。

答案 4 :(得分:0)

当我第一次学习C#时,我在很多个月前写过这个。这是我在VB5天回来的VB函数的转换。该函数的主要好处是没有错误 - 输入将不允许预定义列表之外的任何字符。

/***********************************************************************
 * bool ValiText(char inChar,
 *               string valid,
 *               bool editable,
 *               bool casesensitive
 * Description: Validate Input Characters As They Are Input
 * Notes: For each control whose input you wish to validate, just put
 *        e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
 *        In The KeyPress Event
 ***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
    string inVal = inChar.ToString();
    string tst = valid;
    /// Editable - Add The Backspace Key
    if (editable) tst += ((char)8).ToString();
    /// Case InSensitive - Make Them Both The Same Case
    if (!casesensitive)
    {
        tst = tst.ToLower();
        inVal = inVal.ToLower();
    }
    return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
    string tst = valid;
    /// Editable - Add The Backspace Key
    if (editable) tst += ((char)8).ToString();
    return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
    return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}

请注意,这不适用于Web APP。