简体   繁体   English

c# 中的前导逗号导致系统异常

[英]Leading comma in c# causes system exception

I have to return the maximum number from a series of numbers.我必须从一系列数字中返回最大数字。 I have an edge case in which I may get a leading comma.我有一个边缘情况,我可能会得到一个前导逗号。 How can I remove the leading comma so that the app doesn't break?如何删除前导逗号以使应用程序不会中断?

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));
        }
    }
}

if thats the only problem then you can do:如果那是唯一的问题,那么您可以这样做:

foreach (string x in dataSet)
{
    if (Int32.TryParse(x, out int x2))
        parsedDataSet.Add(x2);
}

The issue should not be the leading comma, but the empty string that split generates for the "before".问题不应该是前导逗号,而是 split 为“之前”生成的空字符串。

So check that string for validity before parsing.因此,在解析之前检查该字符串的有效性。 String.isNullorWhitespace() can do it. String.isNullorWhitespace()可以做到。 But it is propably better to use TryParse() rather then Parse (wich will be called by Convert.ToInt32() ).但是使用TryParse()而不是Parse可能更好(将由Convert.ToInt32()调用)。 Parse is the poster child of throwing vexing Exceptions. Parse 是抛出令人烦恼的异常的典型代表。 Wich is why TryParse() was added with the first Framework Update, 2.0这就是为什么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 returns a string that you try to assign to a List<string> and you never use dataset after, so your design is flawed. string.Join返回一个您尝试分配给List<string> string字符串,之后您再也不会使用dataset ,因此您的设计存在缺陷。

Also you must write TrimStart(',') because it takes a char and not a string.此外,您必须编写TrimStart(',')因为它需要一个字符而不是字符串。

You only need, as others mentioned, to int.TryParse and check if the result is true to add the converted value on success:正如其他人所提到的,您只需要int.TryParse并检查结果是否为真,以便在成功时添加转换后的值:

foreach ( string x in dataSet )
{
  if ( int.TryParse(x, out var value) )
    parsedDataSet.Add(value);
}

So you can remove the try catch.所以你可以删除try catch。

If your string has a starting comma, then the resulting array will have its first element empty.如果您的字符串以逗号开头,则结果数组的第一个元素将为空。 Because you don't want those, tell Split to not return empty elements to begin with:因为你不想要这些,所以告诉Split 不要返回空元素:

List<string> dataSet = userInput.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM