gpt4 book ai didi

c# - 将多个用户输入添加到列表 c#

转载 作者:行者123 更新时间:2023-12-02 15:29:30 28 4
gpt4 key购买 nike

我正在尝试从用户那里获取用户输入,直到用户未输入任何内容(因此按下回车键),但它似乎无法正常工作。用户应该能够添加任意数量的数字,并且一旦他们在没有输入数字的情况下按下回车键就应该显示它们。

代码:

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

namespace Lab2
{
class Program
{
static void Main(string[] args)
{
List<string> numbersInput = new List<string>();

Console.WriteLine("Please enter an integer");
string input = Console.ReadLine();
numbersInput.Add(input);


while (input != "")
{
Console.WriteLine("Please enter another integer: ");
input = Console.ReadLine();
}

if (input == "")
{
Console.WriteLine("The number you have entered is: " + " " + input);
numbersInput.Add(input);
foreach (string value in numbersInput)
{
Console.WriteLine("The number that was added to the list is : " + " " + value);
}
Console.ReadLine();
}
}
}
}

最佳答案

除了空字符串,您没有向 numbersInput 列表添加任何内容。

 if (input == "") // Why do anything with input if you enter this block?
{
Console.WriteLine("The number you have entered is: " + " " + input);
numbersInput.Add(input);
foreach (string value in numbersInput)

numbersInput.Add(input) 需要放在 while block 中。

试试这个

while (input != "")
{
Console.WriteLine("Please enter another integer: ");
input = Console.ReadLine();
numbersInput.Add(input);
}

if (input == "")
{
foreach (string value in numbersInput)
{
Console.WriteLine("The number that was added to the list is : " + " " + value);
}
Console.ReadLine();
}

编辑:求和

更改您的列表声明。

List<int> numbersInput = new List<int>();

然后解析出数字并将它们添加到列表中。如果解析失败,则需要处理错误。

while (input != "")
{
Console.WriteLine("Please enter another integer: ");
input = Console.ReadLine();
int value;
if(!int.TryParse(input, out value))
{
// Error
}
else
{
numbersInput.Add(value);
}
}

然后你的列表不再是一个字符串,所以改变foreach

int sum = 0;
foreach (int value in numbersInput)
{
sum += value;
Console.WriteLine("The number that was added to the list is : " + " " + value.ToString());
}

关于c# - 将多个用户输入添加到列表 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596078/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com