Error 2 Use of unassigned local variable 'Y'

我与影子孤独终老i 提交于 2019-12-11 10:25:59

问题


Again i run into an error i don't mean to bug anyone but I'm getting an error on this code:

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

namespace Input_Program
{
    class Program
    {
       private static void Main()
        {

           char Y;
            char N;

           Console.WriteLine("Welcome to my bool program!");
           Console.WriteLine("Input a NON capital y or n when told to.");




            if(Y == 'y')
            {
                Console.WriteLine("Thank you,Please wait.....");
            }
        }
    }
}

Thanks for you answers!


回答1:


Your variable char Y is not initialized before using. Try to give a default value when declaring.

EDIT It seems that you want the users to input something, and assign it to the variable Y. Try:

Y = Console.ReadKey().KeyChar;



回答2:


if(Y == 'y')

Y is a local variable which isn't assigned anything. So, you assign it any value before the if statement to make any comparison.

Y = 'a';  // or some character 



回答3:


You're not setting Y to anything, and you're also not reading anything from the keyboard.




回答4:


You could explicitly set it to null.

char Y = '<whatever_is_the_default_char>';

That would get rid of the compiler error.

The root cause of the compiler error is that when it goes to compile the if conditional nothing as been assigned to Y. The above is considered an assignment.



来源:https://stackoverflow.com/questions/5400485/error2use-of-unassigned-local-variable-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!