我很难找到第一个方法
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();
}
答案 0 :(得分:1)
获取用户输入以决定下一个字符串数组中的元素数量
您可以在创建数组大小时输入变量,如下所示:
string[] nameOfCountries = new string[someVariable];
someVariable
必须是int
。 Console.WriteLine
返回一个字符串,因此您需要将字符串解析为int。您可以使用int.Parse
。所以:
int numberOfCountries = int.Parse(Console.ReadLine());
string[] nameOfCountries = new string[numberOfCountries];
请注意,Parse
如果无法将输入正确解析为整数,则会抛出异常。
是否还有一种方法可以显示元素编号和字符串元素
在为数组赋值时,可以像使用类似的循环。
Console.WriteLine("{0}: {1}", i, nameOfCountries[i]);
答案 1 :(得分:0)
计划:
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());
}