[英]Leading comma in c# causes system exception
我必须从一系列数字中返回最大数字。 我有一个边缘情况,我可能会得到一个前导逗号。 如何删除前导逗号以使应用程序不会中断?
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Exercises
{
public static void findMax()
{
Console.WriteLine("Enter a series of numbers: ");
string userInput = Console.ReadLine();
List<string> dataSet = userInput.Split(',').ToList();
List<int> parsedDataSet = new List<int>();
try
{
foreach (string x in dataSet)
{
parsedDataSet.Add(Convert.ToInt32(x));
}
}
catch(SystemException)
{
dataSet = String.Join(",", dataSet).TrimStart(","); // <-- Here
}
var maxInput = parsedDataSet.Max();
Console.WriteLine(String.Format("The maximum number within your list is: {0}",maxInput));
}
}
}
如果那是唯一的问题,那么您可以这样做:
foreach (string x in dataSet)
{
if (Int32.TryParse(x, out int x2))
parsedDataSet.Add(x2);
}
问题不应该是前导逗号,而是 split 为“之前”生成的空字符串。
因此,在解析之前检查该字符串的有效性。 String.isNullorWhitespace()
可以做到。 但是使用TryParse()
而不是Parse
可能更好(将由Convert.ToInt32()
调用)。 Parse 是抛出令人烦恼的异常的典型代表。 这就是为什么TryParse()
在第一个框架更新 2.0 中添加的原因
foreach (string x in dataSet)
{
int parsed;
bool success = Int32.TryParse(x, out parsed);
if(success){
parsedDataSet.Add(parsed);
}
else{
//parsed has to be set by compiler rules for out.
//So it is 0 at this. You propably do not want add it to that collection
//Indeed the else is only here for that comment.
}
}
string.Join
返回一个您尝试分配给List<string>
string
字符串,之后您再也不会使用dataset
,因此您的设计存在缺陷。
此外,您必须编写TrimStart(',')
因为它需要一个字符而不是字符串。
正如其他人所提到的,您只需要int.TryParse
并检查结果是否为真,以便在成功时添加转换后的值:
foreach ( string x in dataSet )
{
if ( int.TryParse(x, out var value) )
parsedDataSet.Add(value);
}
所以你可以删除try catch。
如果您的字符串以逗号开头,则结果数组的第一个元素将为空。 因为你不想要这些,所以告诉Split
不要返回空元素:
List<string> dataSet = userInput.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.