简体   繁体   中英

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".

So check that string for validity before parsing. String.isNullorWhitespace() can do it. But it is propably better to use TryParse() rather then Parse (wich will be called by Convert.ToInt32() ). Parse is the poster child of throwing vexing Exceptions. Wich is why TryParse() was added with the first Framework Update, 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.

Also you must write TrimStart(',') because it takes a char and not a string.

You only need, as others mentioned, to int.TryParse and check if the result is true to add the converted value on success:

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

So you can remove the 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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