0

私はあなたの名前を尋ねるアクティビティを行っています。数字が挿入された場合、入力が無効であることがわかるはずです。

これが私のコードです:

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

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

出力例:

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

私の例外が間違っていることはわかっています。皆さんの助けが必要です。

4

3 に答える 3

10

例外の目的を誤解しているようです。

プログラムの実行中にエラーが発生すると、例外がスローされます。たとえば、文字を int に割り当てると、エラーがスローされます。意見はさまざまですが、私は例外を除いてユーザー入力エラーを処理しない傾向があります。さらに、コードに記述したロジックについて考えてください。プログラムは、fname という名前の変数に数値を入力することが正しくないことをどのようにして知ることができますか?

プログラムにロジックを記述して、入力エラーをテストし、適切な応答を返します。あなたの場合、数字が入力されていないことを確認したい場合は、次のことができます。

if (name.Any(char.IsNumber))
{
    Console.WriteLine("Invalid Name.");
}
Console.ReadLine();
于 2012-11-10T09:47:39.103 に答える
0

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.

于 2012-11-10T09:52:24.210 に答える
-3

返信の礼儀として、ここに答えがあります。

ヒント: あなたの例外は正しいです!

コンソールに「Glee」と入力すると、例外はスローされません。

「7337」と入力すると、例外がスローされます。

使用してみてください: fname.ToString();

于 2012-11-10T09:45:20.647 に答える