黑马程序员-c#基础加强版之方法控制流复习-2变量是否初始化的问题

--------------------- ASP.Net+Android+IOS开发.Net培训期待与您交流! ----------------------

 

 今天在看老师讲课的时候,发现一个问题,即上上篇学习笔记《小菜学try语句,又被trouble给cathch住了》里提到的变量未被赋值(没有初始化)的问题.以下左边的代码为老师写的代码,MyFirstMehod方法里的num变量声明时也未赋值(没有初始化),可是并没有报错.右边为之前我写的一个ReadInt的方法,编译错误,错误为:使用了为赋值的局部变量Num1.我感觉二者没有什么差别,为什么左边的MyFirstMethod方法没有错误,而右边的ReadInt方法就有错误.

                                                                                                            

 

static void MyFirstMehod(){
      int num;
      Console.WriteLine("请输入一个数字");
      string str = Console.ReadLine();
      while (true){
         try{
             num=Convert.ToInt32(str);
             break;
          }
          catch{ 
             Console.WriteLine("输入有误,请重输");
              str = Console.ReadLine();
          }
     }   
       Console.WriteLine( num);
  }

 

  

 

 

 

static void ReadInt(){
   int Num1;
   bool IsNumber = false;
   do{
      Console.WriteLine("请输入一个整数");
      try{
        Num1=Convert.ToInt32(Console.ReadLine());
        IsNumber = true;
        }
      catch{
         Console.WriteLine("您的输入有误");
         }
     }while (IsNumber == false);
     Console.WriteLine(Num1);
  }

 

 

 

 

 我将ReadInt()方法改为:

        static void ReadInt()
        {
            int Num1;
            do
            {
                Console.WriteLine("请输入一个整数");
                try 
                {
                    Num1 = Convert.ToInt32(Console.ReadLine());
                    break;
                }
                catch
                {
                    Console.WriteLine("您的输入有误");
                }
            } while (true);
            Console.WriteLine(Num1);
        }

这样就不存在Num1没有被赋值的错误了.为什么呢?

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值