1

我正在寻找一种方法来将用户输入的值分配给我拥有的变量,但要使用循环来获取该条目并将其定位在屏幕上。有没有办法做到这一点?

下面是我的非工作代码,但希望它可以提供我想要实现的目标。

public void StudentDetailInput()
    {
        const int startpoint = 2;
        string[] takeinput = new string[] {FirstName, Surname, MiddleName, StudentId, Subject, AddressLine1, AddressLine2, Town, Postcode, Telephone, Email };

        for (int x = 0; x < takeinput.Length; x++)
        {
            Console.SetCursorPosition(30, startpoint + x);
            [x] = Console.ReadLine();
        }
    }
4

3 回答 3

4

您可能想使用字典:

private Dictionary<string, string> _answers = new Dictionary<string, string>();

public void StudentDetailInput()
{
    string[] takeinput = new string[] { 
        "FirstName", 
        "Surname",
        "MiddleName",
        "StudentId",
        "Subject",
        "AddressLine1", 
        "AddressLine2",
        "Town", 
        "Postcode", 
        "Telephone",
        "Email" 
    };

    _answers.Clear();
    for (int x = 0; x < takeinput.Length; x++)
    {
        Console.Write(takeinput[x] + ": ");
        var answer = Console.ReadLine();
        _answers.Add(takeinput[x], answer);

    }
}

所以你可以像这样显示答案:

for(var i = 0; i < _answers.Count; i++)
{
    Console.WriteLine("{0}: {1}", _answers.Keys[i], _answers.Values[i]);
}

如果您担心您不想在控制台上使用这么多行,您可以跟踪答案的长度并尝试将光标放在到目前为止的答案后面。这样做的问题是您需要考虑屏幕的宽度(可以由用户调整)来计算正确的行和位置。

这种结构的另一个问题是用户会期望光标向下移动一行(这就是 enter 所做的),因此用户体验可能会受到影响。

另一种方法是在每次输入后清除屏幕,从控制台的第 2 行开始显示到目前为止的所有答案,并将下一个问题放在第 1 行:

for (int x = 0; x < takeinput.Length; x++)
{
    Console.Clear();
    for(y = 0; y < x; y++)
    {
        Console.SetCursorPosition(0, y + 1);
        Console.WriteLine("{0}: {1}", _answers.Keys[y], _answers.Values[y]);
    }
    Console.SetCursorPosition(0, 0);
    Console.Write(takeinput[x] + ": ");
    var answer = Console.ReadLine();
    _answers.Add(takeinput[x], answer);
}

当问题的数量多于控制台上的行数时,这可能会出错。

于 2013-04-19T07:14:12.180 回答
1

您的字符串数组定义不清楚,但我认为您正在寻找这样的东西:

public void StudentDetailInput()
{
    const int startpoint = 2;
    string[] takeinput = new string[11];

    for (int x = 0; x < takeinput.Length; x++)
    {
        Console.SetCursorPosition(30, startpoint + x);
        takeinput[x] = Console.ReadLine();
    }
}

现在

// FirstName = takeinput[0]
// Surname   = takeinput[1]
// ...
于 2013-04-19T06:29:30.523 回答
0

这条线是错误的。

[x] = Console.ReadLine();

如果你想分配给你的数组元素,你用ReadLine()方法读取的内容,你应该使用

takeinput[x] = Console.ReadLine();

如果您只想分配计数器所读取的内容,则应使用;

x = Convert.Int32(Console.ReadLine());

编辑:如果我清楚地理解您的问题,您只想这样做;

List<string> list = new List<string>();
string input = "";

do
{
   input = Console.ReadLine();
   list.Add(input);
}
while (input != "exit");
list.Remove("exit");

foreach (var item in list)
{
   Console.WriteLine(item);
}
于 2013-04-19T06:34:20.660 回答