新手问题:
假设我有一个可以存储10个值的int数组
如何将用户输入1次仅填充1个括号,然后停止直到新用户存储值?我只知道如何在循环中填充数组,但我猜测没有循环用于存储1个值。
你可能想要这样的东西:
public static void Main()
{
int[] arr = new int[10];
int i = 0;//counter
while(i<arr.Length)
{
Console.Write("Enter an integer: ");
if (int.TryParse(Console.ReadLine(), out arr[i]))
{
i++;
Console.WriteLine("\nPress enter to continue!");
Console.ReadLine();
}
else
{
Console.WriteLine("\nYou didn't enter an integer!\n");
}
}
}
不完全确定你的意思,但这不会一直要求用户提供输入,它只询问一次:
class Program
{
static void Main(string[] args)
{
int[] arr = new int[9];
Console.WriteLine("Enter a value: ");
arr[0] = int.Parse(Console.ReadLine());
//Console.WriteLine(arr[0]);
}
}
你可以从List<>
开始,然后当你知道你准备就绪时,你可以将它转换为数组。使用List,可以轻松添加项目。
int[] GetUserInput()
{
var list = new List<int>();
while (true)
{
Console.WriteLine("Enter a value or just press enter to indicate you are done.");
var s = Console.ReadLine();
if (string.IsNullOrEmpty(s)) break;
list.Add(int.Parse(s));
}
return list.ToArray();
}