给出错误说明未分配局部变量

时间:2014-04-23 02:52:04

标签: c# variables

这是我为解决数学问题而编写的一个简单代码。

namespace StoreCredit
{
    class Program
    {
        private static int No1;
        static void Main(string[] args)
        {
            string[] text = System.IO.File.ReadAllLines(@"input.txt");

            int nocases = int.Parse(text[0]);
            int J = 1;
            int No1=0;
            int No2=0;
            for (int x = 1; x <= nocases;x++ )
            {
                int Amount = int.Parse(text[J]);
                int NoItem = int.Parse(text[J+1]);

                char[] delimiterChars = { ' ' };

                string[] Values = text[J+2].Split(delimiterChars);

                int z = 0;
                bool found = false;
                while ((z < NoItem) && !found)
                {
                    int Item = int.Parse(Values[z]);

                    int Remaining = Amount - Item;

                    int y = 0; bool found2 = false;
                    while ((y < NoItem) && !found2)
                    {
                        if (Remaining == int.Parse(Values[y])&&!(y==z))
                        {
                            Console.WriteLine("Found a match");
                            found = true;
                            found2 = true;
                            Console.WriteLine("Value 1 = {0} and Value 2={1}",(z+1),(y+1));
                        }
                        y++;
                    }

                    z++;
                }

                string lines = "Case #" + x + ": ", z, y;
                StreamWriter file2 = new StreamWriter(@"output.txt", true);
                file2.WriteLine(lines);
                file2.Close();

                J = J + 3;
            }
        }
    }
}

我想把这个程序的输出写入文本文件。但是我得到一个错误,说z,y不能在这个范围内声明,因为它会给z,y赋予不同的含义。能否请你解释一下原因。

谢谢

1 个答案:

答案 0 :(得分:3)

这一行接近结束时会尝试重新声明zy,因为您已用逗号分隔它们:

string lines = "Case #" + x + ": ", z, y;

你打算连接它们吗?如:

string lines = "Case #" + x + ": " + z + y; // notice the + instead of comma