简体   繁体   中英

String FormatException

I'm doing an activity that asks your name, and if a number is inserted it should tell that the input is invalid.

Here's my code:

 try {
            Console.Write("Enter your first name: ");
            string fname = Console.ReadLine();
            Console.Write("You're Name is: " + fname);

        }
        catch (Exception) {
            Console.Write("INVALID NAME");
        }

Sample output:

Enter you're first name: 123hjay
INVALID NAME!!

I know my exception is wrong; I need your help guys.

You seem to have misunderstood the purpose of exceptions.

Exceptions are thrown when a program encounters an error in its execution . For example assigning a letter to an int would throw an error. While opinions vary, I tend not to handle user input errors with exceptions. Furthermore, think about the logic you wrote in your code. How could the program know that entering numbers into a variable named fname is incorrect?

Write in logic into your program to test for input errors and then return an appropriate response. In your case, if you wanted to ensure that there were no numbers entered, you could do the following:

if (name.Any(char.IsNumber))
{
    Console.WriteLine("Invalid Name.");
}
Console.ReadLine();

As my comment says (in the question), I didn't really get what it is you are asking, because it doesn't throw anything, but if you did want it to throw an error (also suggested by the comments), this should help:

        Console.Write("Enter you're first name: ");
        string fname = Console.ReadLine();

        foreach (var character in fname)
        {
            if (Char.IsDigit(character))
                throw new Exception("Numbers are not allowed.");
        }

        Console.Write("You're Name is: " + fname);

It's very straight forward and you can read it as English and understand what I've done. You can mess around with the code, look at similar functions with Visual Studios IntelliSense and tweak it to your needs.

If you need, add a try & catch blocks, of course.

for the courtesy of replying back, here is the answer.

Hint: your exception is right!

Enter in your console "Glee" it will not throw exception.

If you type "7337" it does throw exception.

try to use : fname.ToString();

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