c# - 为什么输入字符串格式不正确且未处理异常
问题描述
从用户获取数组输入时出现错误。
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;
}
要将数组大小和元素以及我们需要在用户提供的给定数组元素之间进行比较的数字作为输入,并返回其和等于给定数字的可能对。
解决方案
我不确定我是否遇到了与您相同的问题,但我将您的代码修改如下。起初,我为整数创建了一个安全的控制台 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);
}
这样我的测试就成功了。请注意,我没有替换 j 的最后一个 Convert.ToInt32。
请注意,请始终尽可能验证用户输入,以免引发异常。如果任何时候你会检查任何不正确的东西,它肯定会在某个时候崩溃......
祝你有美好的一天!
推荐阅读
- keras - 如何使用 ktrain 包连接表格和文本数据?
- sql - 在oracle中通过查询将列转换为行
- android - getOrientation 函数返回的音高错误
- ruby-on-rails - RAILS:用外部约束截断和替换 postgres 表上的数据
- node.js - 是否可以将原生 Windows 窗口的实时图像嵌入/流式传输/投影到网页中?
- javascript - 在 Material-Table 中的 Azure Kubernetes 服务器中排序和选择不起作用
- python - 使用 geopandas、geoplot 和 matplotlib 的 Shapefile 地形投影不显示所有数据
- python - 在事件触发时更新 wxpython 中的静态标签
- apache-flink - 从自定义分区键中提取类型时出错
- java - 在 Java 中创建嵌套对象而不创建类