从用户处获取数组输入时出现错误。
static void Main(string[] args)
{
int[] arrSum = new int[] { };
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for (int i = 0; i < n; i++)
{
arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);
}
public static int ArraySum(int[] arr, int key, int n)
{
for (int i = 0; i < arr.Length; i++)
{
int first = arr[i];
for (int k = i+1; k < arr.Length; k++)
{
int second = arr[k];
while (first + second == key)
{
Console.WriteLine("The numbers whose sum is {0}" + key + "are:\n" + first + second);
}
if (first + second != key)
{
return -1;
}
else
{
return 1;
}
}
}
return 0;
}
要获取数组大小和元素以及其和的数目,我们需要在用户的给定数组元素之间进行比较作为输入,并返回其和等于给定数目的可能对。
答案 0 :(得分:0)
我不确定是否遇到与您相同的问题,但是我按如下方式修改了您的代码。最初,我为整数创建了一个安全的控制台readline方法,如果输入了无效的整数,则不会引发异常:
private static int GetIntFromInput()
{
while (true)
{
string value = Console.ReadLine();
if (!int.TryParse(value, out int parsedInt))
{
Console.WriteLine("Invalid integer! Retry or Ctrl+C to abort program...");
continue;
}
return parsedInt;
}
}
然后我将您的第一种方法修改如下:
static void Main(string[] args)
{
Console.WriteLine("Enter the array Size:\t");
int n = GetIntFromInput();
if (n <= 0)
{
Console.WriteLine("Array has to be at least of size 1...");
return;
}
Console.WriteLine("Enter the array elements of {0} as Array Size:\n", n);
var arrSum = new int[n];
for (int i = 0; i < n; i++)
{
int newInt = GetIntFromInput();
arrSum[i] = newInt;
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum, n, j);
}
以此,我的测试成功了。请注意,我没有将最后一个Convert.ToInt32替换为j。
请注意,请始终验证用户输入,以免引发异常。如果您有任何时间检查不正确的内容,肯定会导致崩溃...
祝你有美好的一天!
答案 1 :(得分:0)
我刚刚修改了数组输入代码行,非常简单。如果您想支票,也可以使用Correct me if I’m wrong, but I think all of these are the same thing:
• GameDrawer * gameDrawer;
• GameDrawer* gameDrawer;
• GameDrawer *gameDrawer;
int.TryParse