日期:2014-05-17  浏览次数:20653 次

本人初学C# 求看一段简单代码错误问题及解决方案
本帖最后由 ManaStuDent 于 2013-01-04 21:41:13 编辑

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            Console.WriteLine("请输入一个数字");
            try
            {
                a = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("请输入一个数字");
            }
            for (int i = 1; i < 10; i++)
            {
                if (a > 10)
                {
                    Console.WriteLine("Hello Word !");
                }
            }
            Console.ReadKey();
        }
    }
}



if  后面的a 报错
c#

------解决方案--------------------
变量声明时候就初始化 int a=0;
------解决方案--------------------
如果开始输入非数字,进入catch,接着输入任意进入for循环里的if(a>10),报错:使用了未赋值的局部变量。
变量声明即初始化是个好习惯,可以避免很多不必要的错误。
------解决方案--------------------
代码改为下面这样

for (int i = 1; i < 10; i++)            
{                
if (a > 10)                
{                    
Console.WriteLine("Hello Word !");                
}            
}
的代码放到
try 块中的
a = Convert.ToInt32(Console.ReadLine());
代码行下面