简体   繁体   中英

Input string was not in a correct format, List<String> to Dictionary<int, int>

I am trying to create a program that reads user inputted integers from the console, then creates a Dictionary<int, int> , and finally prints all inputs with the number of times they have been entered. My idea was to collect each entry until an empty line in a List. Then I would parse it and create the dictionary with input for Key and times typed as Value.

I get "Unhandled Exception: System.FormatException: Input string was not in a correct format" at int integer = int.Parse(number); and nothing gets printed.

Would you please help me understand where the code falls apart. I am a beginner and not sure how to correct it.

static void Main(string[] args)
    {
        string input = "0";
        List<string> listNumbers = new List<string>();
        Console.WriteLine("Type several numbers and press Enter after each one:");
        while (input != string.Empty)
        {
            input = Console.ReadLine();
            listNumbers.Add(input);
        }

        IDictionary<int, int> intOccurences = new Dictionary<int, int>();
        foreach (string number in listNumbers)
        {
            int integer = int.Parse(number);
            int count;
            if (!intOccurences.TryGetValue(integer, out count))
            {
                count = 0;
            }
                intOccurences[integer] = count + 1;
        }
        PrintNumbers(intOccurences);
    }
        private static void PrintNumbers(IDictionary<int, int> intOccurences)
    {
        foreach (KeyValuePair<int, int> entry in intOccurences)
        {
            Console.WriteLine(
                "Number '{0}' occurs {1} time (s) in the input.", entry.Key, entry.Value);
        }
    }

Consider using TryParse :

        string possibleInteger ="12";
        int resultInteger;
        bool isCorrectInteger = int.TryParse(possibleInteger, out resultInteger);
        if (isCorrectInteger)
        {
            // add to dictionary
        }
        else
        {
            Console.WriteLine("Not a correct integer number");
        }

Also, remember to consider your Culture settings while parsing numbers and dates. For example if the current language uses/doesn't use some decimal separator or thausand separator, you may end up with format exceptions. If it is a factor in your case, consider using the version of TryParse that takes it into account.

Possible solution

Replace

int integer = int.Parse(number);

With

int integer;

var isInteger = int.TryParse(number, out integer);

if(!isInteger) continue; // Not a number skip

if (!intOccurences.TryGetValue(integer, out count))
{
                count = 0;
}
  • Idea remains, skip the non integers, else devise a mechanism to handle them. You cannot int.parse(<Non Integer>)

You could try directly converting to integers immediately after reading a line from the console, adding them to a list of integers. This makes everything easier to understand as well. For example:

IDictionary<int, int> intOccurences = new Dictionary<int, int>();
List<int> allInputs = new List<int>();
while (input != string.Empty)
{
    input = Console.ReadLine();
    allInputs.Add(Convert.ToInt32(input));
}
foreach (int i in allInputs)
{
    int currentCount; //defaults to 0
    intOccurences.TryGetValue(i, out currentCount);
    frequencies[i] = currentCount + 1;
}

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