1

该程序将给我错误消息:

使用未分配的变量 yourName 和使用未分配的变量 yourIsp。

如果我取出 for 循环,它将运行。我试图向用户询问姓名和 isp 至少 4 次,并使用字符串操作从名字和姓氏创建电子邮件地址。

static void Main(string[] args)
{
    string yourName; string yourIsp;
    Console.WriteLine("Enter your full name:");
      for (int i = 0; i < 4; i++)            
    yourName = Console.ReadLine();

    Console.WriteLine("Enter your ISP:");
      for (int j = 0; j < 4; j++)
    yourIsp = Console.ReadLine();

    char[] separator = {' '};
    string[] yourWords;
    yourWords = yourName.Split(separator);
    string yourFirstName = yourWords[0];
    string yourLastName = yourWords[1];
    string yourEmailAddress = yourFirstName + yourLastName + "@" + yourIsp;
    yourEmailAddress = yourEmailAddress.ToLower();
    Console.WriteLine("Hello {0}, your email address is {1}", yourName, yourEmailAddress);
}   
4

3 回答 3

0

您必须给出yourName默认yourIsp值。

string yourName = "";
string yourIsp = "";

它不知道您的for循环是否肯定会运行(即使您可以知道它们每个都会运行 4 次)


想象一下,如果您的循环看起来像这样:

int number;

for (int i = 0; i < someList.Count(); i++)
    number = Math.Max(number, i.SomeValueInTheList);

Console.WriteLine("Largest value in list: {0}", number);

如果列表中没有元素,则循环将永远不会运行,number也不会被初始化。


将值存储在列表中,然后逐一显示。您覆盖值,并丢失除最后一个输入值之外的所有值。

var names = new List<string>();
var isps = new List<string>();

string yourName; string yourIsp;
Console.WriteLine("Enter your full name:");
for (int i = 0; i < 4; i++)
    names.Add(Console.ReadLine());

Console.WriteLine("Enter your ISP:");
for (int j = 0; j < 4; j++)
    isps.Add(Console.ReadLine());

foreach (var sentence in names.Zip(isps, (name, isp) => string.Format("Hello {0}, your email address is {1}", name, string.Concat(name, "@", isp).ToLower())))
    Console.WriteLine(sentence);
于 2014-02-03T01:16:57.333 回答
0

更改string yourName; string yourIsp;为:

string yourName = null;
string yourIsp = null;

问题是编译器无法安全地判断是否曾经为变量分配了值。虽然从代码中可以清楚地看出会有四次赋值,但这不是编译器能说的。因此,您必须显式地初始化变量。

于 2014-02-03T01:17:30.853 回答
0

现有答案描述了错误。我的帖子解决了我认为您可能一直在尝试做的事情:

for (int i = 0; i < 4; i++) {
    Console.WriteLine("Enter your full name:");
    string yourName =Console.ReadLine();

    Console.WriteLine("Enter your ISP:");
    string yourIsp = Console.ReadLine();

    char[] separator = {' '};
    string[] yourWords;
    yourWords = yourName.Split(separator);
    string yourFirstName = yourWords[0];
    string yourLastName = yourWords[1];
    string yourEmailAddress = yourFirstName + yourLastName + "@" + yourIsp;
    yourEmailAddress = yourEmailAddress.ToLower();
    Console.WriteLine("Hello {0}, your email address is {1}", yourName, yourEmailAddress);
}
于 2014-02-03T01:19:59.280 回答