【问题标题】:How do you get user input to decide how many elements are in a string array?您如何获取用户输入来决定字符串数组中有多少元素?
【发布时间】:2016-11-17 07:48:02
【问题描述】:

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

  1. 获取用户输入以决定下一个字符串数组中有多少元素
  2. 然后将用户输入从字符串转换为数组的int
  3. 还有一种方法可以像这样显示元素编号以及字符串元素......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 numberOfCountries = Console.ReadLine(); 是干什么用的?
  • 如果问题得到解决,请将对您有帮助的答案标记为已接受的答案(小复选标记)并给予支持。
  • 通常更容易/更简单地使用List&lt;string&gt; 并要求输入空白以完成列表。

标签: c#


【解决方案1】:

获取用户输入来决定下一个字符串数组中有多少元素

你可以在创建数组大小的时候放入一个变量,像这样:

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[] nameOfCountries = new string[someVariable];它提示我 Error CS0029 , cannot convert int to string 有什么办法解决这个问题?
  • @keanu.b 我的示例代码有误。 See here 了解编辑详情。
  • 其实没关系,我想通了,谢谢你的帮助!!
  • 是的,没问题,一旦我弄清楚了,我最终将其更改为 int 哈哈
  • 或者,使用 TryParse。
【解决方案2】:

程序:

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&lt;string&gt; 可能会更好地存储这样的数据。然后你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多