我试图将整数输入保存到一个数组中,但它不起作用。我从 How to Fill an array from user input C#? 中找到了一个字符串保留示例
string[] yazi = new string[15];
for (int i = 0; i < yazi.Length; i++)
{
yazi[i] = Console.ReadLine();
}
但是当我将这段代码转为整数时,它报错了
int[] sayis = new int[20];
for (int k = 0; k < sayis.Length; k++)
{
sayis[k] = int.Parse(Console.ReadLine());
}
我错过了什么吗?
最佳答案
Am I miss something?
错误信息,一方面...
应该没问题 - 只要您在控制台中输入整数即可。 (我刚刚试过了,效果很好。)如果用户输入的值不能被解析为整数,您将得到一个 FormatException
.您应该考虑使用 int.TryParse
相反......这将在 out
参数中设置值,并返回它是否真的成功了。例如:
for (int k = 0; k < sayis.Length; k++)
{
string line = Console.ReadLine();
if (!int.TryParse(line, out sayis[k]))
{
Console.WriteLine("Couldn't parse {0} - please enter integers", line);
k--; // Go round again for this index
}
}
关于c# - 将整数输入保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954959/