How do I prevent crashing due to invalid input in

2020-02-13 06:04发布

The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.

What I want to do is:

  1. Prevent the program from crashing from invalid input.

  2. Display an error message if the input is invalid

  3. Have the program continue where it left off, without affecting the rest of the program.

Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?

This is in C#

My code:

using System;

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

namespace 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);
    }
}

}

标签: c# input crash
5条回答
唯我独甜
2楼-- · 2020-02-13 06:10
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));
}
查看更多
Summer. ? 凉城
3楼-- · 2020-02-13 06:11
int value = 0;
if (!int.TryParse(input, out value))
{
    MessageBox.Show("Oops");
} else {
    // use the value in the variable "value".
}
查看更多
The star\"
4楼-- · 2020-02-13 06:12

Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.

查看更多
狗以群分
5楼-- · 2020-02-13 06:19

Here you go:

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.");
                }
            }
        }
    }
}
查看更多
爷、活的狠高调
6楼-- · 2020-02-13 06:27

I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.

/***********************************************************************
 * 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;
}

Note That This Will Not Work On A Web APP.

查看更多
登录 后发表回答