C#方法练习

1.计算两个整数间的最大值

using System;
using System.Reflection.Metadata.Ecma335;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            int a1 = 10;
            int a2 = 20;
            GetMax(a1, a2);//实参
        }

        
        /// <summary>
        /// 计算两个整数之间的最大值,并且返回最大值
        /// </summary>
        /// <param name="n1">第一个值</param>
        /// <param name="n2">第二个值</param>
        /// <returns>返回最大的值</returns>
        public static int GetMax(int n1,int n2)//形参
        {
            int max = n1 > n2 ? n1 : n2;
            return max;
        }
        // 不管是形参还是实参,都是在内存中开辟了空间的。
        //     
        //     方法的功能一定要单一。
        // 方法中最忌讳的就是出现提示用户输入的字眼。
    }
}

2.读取输入的整数,定义成方法,多次调用(如果用户输入的是数字,则返回,否则提示用户重新输入)

using System;

namespace 函数方法练习
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个整数:");
            string input = Console.ReadLine();
            int number = GetNumber(input);
            Console.WriteLine(number);
            // Console.ReadKey();
        }

        public static int GetNumber(string s)
        {
            while (true)
            {
                try
                {
                    int number = Convert.ToInt32(s);
                    return number;
                }
                catch
                {
                    Console.WriteLine("请重新输入:");
                    s = Console.ReadLine();
                }
            }
        }
    }
}

用户只有输入Yes或者No才会返回Yes或者No,输入其他字符需要重新输入

using System;

namespace 输入YorN
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入Yes或者No");
            string input = Console.ReadLine();
            string result = IsYesOrNo(input);
            Console.WriteLine(result);
        }
        

        /// <summary>
        /// 限定用户只能输入Yes或者No 并且返回
        /// </summary>
        /// <param name="input">用户的输入</param>
        /// <returns>返回Yes或者No</returns>
        public static string IsYesOrNo(string input)
            {
                while (true)
                {
                    if (input == "Yes" || input == "No")
                    {
                        return input;
                    }
                    else
                    {
                        Console.WriteLine("只能输入Yes或者No,请重新输入");
                        input = Console.ReadLine();
                    }
                }
            }
    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值