简体   繁体   中英

C# - How can I create an exception for non-numeric on this code?

I want to create an exception, preferebly with Try/catch from this code when I type a non-numeric character. I tried with int.TryParse, but this only return 0 when I use a non-numeric character. But don't show me any error message, but with int.Parse (Console.ReadLine) I got an error message:

The string of input characters was not in a correct format.

Code

while (true)
{         
    Console.WriteLine("TYPE A NUMBER HIGHER THAN 20: ");
    int number;
    number = int.Parse(Console.ReadLine());
    if (number> 20)
    {
        Console.WriteLine("O NÚMERO DIGITADO FOI: " + number);
        break;
    }

    else
    {
        Console.WriteLine(number+ " é menor do que 20, favor digitar um número maior");

    }              
}    
Console.ReadLine();

You can create an exception like this:

Console.WriteLine("Type a number: ");
string line = Console.ReadLine();
    try {
        num = Int32.Parse(line);
    } 
    catch (FormatException) {
        Console.WriteLine("{0} is not an integer", line);
    }

Or you can use int.TryParse as you had mentioned:

Console.WriteLine("Type a number: ");
string line = Console.ReadLine();
if (!int.TryParse(line, out num)) {
    Console.WriteLine("{0} is not an integer", line);
}

Instead of throwing an exception you should try to handle the input with Int32.TryParse (instead of Parse):

bool run = true;
while (run)
{
    Console.Write("Type in a number: ");
    string input = Console.ReadLine();

    //Exit application
    if(input == "exit")
    {
        run = false;
        return;
    }

    //Returns true if numberStr can be parsed to an int
    int number;
    if (Int32.TryParse(input, out number))
    {
        //input is a number, now let's do some logic!
        if(number > 20)
            Console.WriteLine("Number is greater than 20!");
        else
            Console.WriteLine("Number is less than 20!");
    }
    else
        Console.WriteLine("Doesn't seem to be a number: " + number);

}

Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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