C#程序設計練習題十一:猜數(C#)

題目描述

編寫一個控制檯程序。以控制檯方式輸入整數,且調用Class1類CompareNum方法判斷是否猜中,給出大了、小了、猜中三種提示。輸入exit表示輸入結束。

輸入

輸出

太小了
太大了
猜中了

提示

若輸入的既不是數字,又不是exit,應給出合理提示。如請輸入數字!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int p = 1;
            while (p > 0)
            {
                string input = Console.ReadLine();
                if (input == null || "".Equals(input))
                {
                    break;
                }
                if (input == "exit")
                    break;
                else if (IsNumeric(input))
                {
                    int m = Convert.ToInt32(input);
                    Class1 zch = new Class1(m);
                    string res = zch.CompareNum(m);
                    Console.WriteLine(res);
                }
                else
                {
                    Console.WriteLine("請輸入數字!");
                    
                }
            }
            Console.ReadKey();
        }
        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }
    }
    public class Class1 
    {
        private int id;
        public Class1(int id)
        {
            this.id = id;
        }
        
        public int MyProperty { get; set; }
        public string CompareNum(int id)//靜態方法
        {
            string res;
            if (id > 100)
                res = "太大了";
            else if (id > 0 && id <= 100)
                res = "猜中了";
            else
                res = "太小了";
            return res;
        }
    
    }
}

 

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