猜数字(C#)

在这里插入图片描述

using System;

namespace practicerandom
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rdm = new Random();
            int guess = rdm.Next(0, 101); 
            bool temp = false;
            try
            {
                int j = 0;
                do
                {
                    Console.WriteLine("请输入一个0到100之间的整数");
                    string sGuess = Console.ReadLine();
                    int Guess = int.Parse(sGuess);
                    if (Guess < 0 || Guess > 100)
                        throw new Exception("The integer does not meet the requirement!");
                    else if (Guess == guess)
                    {
                        temp = true;
                        j++;
                        Console.WriteLine("这是第{0}次猜,恭喜你,猜对了!",j);
                    }
                    else if (Guess > guess)
                    {
                        j++;
                        Console.WriteLine("这是第{0}次猜,太大了",j);
                    }
                    else if (Guess < guess) 
                    {
                        j++;
                        Console.WriteLine("这是第{0}次猜,太小了",j);
                    }
                } while (temp != true);
            }
            catch (Exception e)
            {
                Console.WriteLine("发生的错误为:"+e.Message);
            }

        }
    }
}

try catch语句的使用以及如何抛出异常
在这里插入图片描述

发布了30 篇原创文章 · 获赞 4 · 访问量 904

猜你喜欢

转载自blog.csdn.net/weixin_45776347/article/details/104627674