代码:
string[] numbers = new string[2];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Console.ReadLine();
if (int.TryParse(numbers[i], out int numberTry) && i == 0)
Console.WriteLine("That would be a number yes.");
else if (int.TryParse(numbers[i], out numberTry))
Console.WriteLine("Lovely work! That is indeed two numbers!");
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
我的问题是我不能在循环之外使用数字[]作为int,因为它从循环中的字符串转换为int。我需要能够使用方法作为int发送它来对数字[0]和数字[1]执行操作。 提前谢谢!
答案 0 :(得分:5)
int[] numbers = new int[2];
for (int i = 0; i < numbers.Length; i++)
{
var number = Console.ReadLine();
if (int.TryParse(number, out int numberTry) && i == 0)
{
Console.WriteLine("That would be a number yes.");
numbers[i] = numberTry;
}
else if (int.TryParse(number, out numberTry))
{
Console.WriteLine("Lovely work! That is indeed two numbers!");
numbers[i] = numberTry;
}
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
Console.ReadKey();