猜數字(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語句的使用以及如何拋出異常
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章