如何让用户输入决定字符串数组中有多少个元素

本文关键字:多少 元素 数组 字符串 用户 输入 决定 | 更新日期: 2023-09-27 18:18:30

我正在努力寻找第一种方法

  1. 获取用户输入以决定下一个字符串数组中有多少元素
  2. 然后将Users输入从字符串转换为数组
  3. 的整型
  4. 是否还有一种方法可以显示元素号以及字符串元素,如....Console.WriteLine(1. StringName 2.StringName);

这是我的代码:

Console.WriteLine("How many countries you want mate ? ");
string numberOfCountries = Console.ReadLine();
Console.WriteLine("Please name your countries ");
string[] nameOfCountries = new string[10];
for (int i = 0; i < nameOfCountries.Length ; i++)
{
    nameOfCountries[i] = Console.ReadLine();
}

如何让用户输入决定字符串数组中有多少个元素

获取用户输入以决定下一个字符串数组中将包含多少个元素

在创建数组大小时可以放入一个变量,如下所示:

string[] nameOfCountries = new string[someVariable];

someVariable必须是intConsole.WriteLine返回一个字符串,因此您需要将该字符串解析为int。您可以使用int.Parse。所以:

int numberOfCountries = int.Parse(Console.ReadLine());
string[] nameOfCountries = new string[numberOfCountries];

注意,如果Parse不能正确解析输入为整数,它将抛出异常。

是否还有一种方法可以显示元素号和字符串元素

你可以像给数组赋值时那样使用类似的循环。

Console.WriteLine("{0}: {1}", i, nameOfCountries[i]);

程序:

string mate = "mate";
Console.WriteLine($"How many countries you want {mate}?");
string numberOfCountries = Console.ReadLine();
int numberOfCountriesInt;
while ( !int.TryParse( numberOfCountries, out numberOfCountriesInt ) )
{
    mate = mate.Insert(1, "a");
    Console.WriteLine($"How many countries you want {mate}?");
    numberOfCountries = Console.ReadLine();
}
Console.WriteLine("Please name your countries ");
string[] namesOfCountries = new string[numberOfCountriesInt];
for (int i = 0; i < namesOfCountries.Length; i++)
{
    namesOfCountries[i] = Console.ReadLine();
}
for (int i = 0; i < namesOfCountries.Length; i++)
{
    Console.WriteLine($"{i+1}, {namesOfCountries[i]}");
}
输出:

How many countries you want mate?
Two
How many countries you want maate?
Two?
How many countries you want maaate?
2
Please name your countries
Stralya
PNG
1. Stralya
2. PNG

请注意,List<string>可能更好地存储这样的数据。然后你可以这样做:

Console.WriteLine("Please name your countries ");
var namesOfCountries = new List<string>();
for (int i = 0; i < numberOfCountriesInt; i++)
{
     namesOfCountries.Add(Console.ReadLine());
}