'Getting a system format exception at the int32.parse line

For some reason, I continue to get a system format exception at the int32.parse line. I don’t understand what I’m doing wrong.

My assignment is to:

  1. Create a simple application in which you have variables of appropriate types to store the user’s name and three test grades.
  2. Ask for this information from the user and store it appropriately.
  3. Create a variable to store the user’s test average.
  4. Calculate and assign this value using the stored information given to you by the user.

My code follows:

class MainClass
{
    public static void Main (string[] args)
    {
        Console.WriteLine ("Please enter your name: ");
        string name; 
        name = Console.ReadLine ();
        Console.WriteLine ("Hello, " + name); 
        int score;
        Console.Write ("What are your last three test scores: "); 
        score = Int32.Parse(Console.ReadLine ());
        Console.WriteLine("Your test scores are" + score + "90,92,95");}
}


Solution 1:[1]

It's important to inspect user input in order to avoid Exceptions due to invalid input. Here's how I would do it:

class MainClass
{
    public static void Main(string[] args)
    {
        //Variable Declarations
        string response,
               name;

        string[] scores;

        int sumOfAllScores,
            scoreCount;

        bool validResponse;
        System.Text.RegularExpressions.Regex onlyDigits;

        //We need to assign response an initial value or else Visual Studio will complain
        //since it only receives its real value within a while loop (which as far as the parser is concerned
        //may or may not ever iterate.
        response = string.Empty;

        //Booleans are automatically assigned an intial value of 'false' but I like to intialize them anyway
        validResponse = false;

        //Initialize the score sum and score counter variables.
        sumOfAllScores = 0;
        scoreCount = 0;

        //This Regex pattern will allow us to inspect a string to ensure that it contains only digits.
        onlyDigits = new System.Text.RegularExpressions.Regex(@"^\d+$");

        Console.Write("Please enter your name: ");
        name = Console.ReadLine();
        Console.WriteLine("Hello, " + name);

        //This loop will iterate until the user provides valid input (comma-separated integers).
        while (!validResponse)
        {
            //When we enter the while loop, set validResponse to true.
            //If we encounter any invalid input from the user we will set this to false so that
            //the while loop will iterate again. 
            validResponse = true;

            Console.Write("What are your last three test scores (comma-separated list, please): ");
            response = Console.ReadLine();

            //Split response into an array of strings on the comma characters
            scores = response.Split(',');

            //Inspect each element of the string array scores and take action:
            foreach (string scoreEntry in scores)
            {
                //If the current array member being inspected consists of any characters that are not integers,
                //Complain to the user and break out of the foreach loop.  This will cause the while loop to iterate
                //again since validResponse is still false.
                if (!onlyDigits.IsMatch(scoreEntry))
                {
                    //Complain
                    Console.WriteLine("Invalid response. Please enter a comma-separated list of test scores");
                    Console.WriteLine(Environment.NewLine);

                    //Re-initialize the score sum and score count variables since we're starting over
                    sumOfAllScores = 0;
                    scoreCount = 0;

                    //Set validResponse to false and break out of the foreach loop
                    validResponse = false;
                    break;
                }

                //Otherwise, we have valid input, so we'll update our integer values
                else
                {
                    //Iterate the number of scores that have been entered and validated
                    scoreCount++;

                    //Use the static Convert class to convert scoreEntry to an Integer
                    //and add it to the score sum
                    sumOfAllScores += Convert.ToInt32(scoreEntry);
                }
            }
        }

        //Report the results to the user:
        Console.WriteLine("Your test scores are: " + response);
        Console.WriteLine("Your average score is " + sumOfAllScores / scoreCount);
    }
}

Solution 2:[2]

Console.Readline() returns a string. In your case this string might be something like "96,92,99".

string inputs = Console.ReadLine();

First step would be to split the string into three strings like "96", "92", "99" by using the comma as a separator

string[] parts = input.Split(',');

Now each string needs to be converted into an integer, one by one

// Create array of integers with the same size as the array of parts
int[] grades = new int[parts.Length];
// Loop through the input parts and convert them into integers
for(i=0; i<parts.Length; i++)
{
    // Use `TryParse()` as it wont throw an Exception if the inputs are invalid
    int.TryParse(parts[i], out grades[i]);
}

Now you can do things like calculate an average. I prefer the use the built in functions like .Average() or .Sum()

Console.WriteLine("The average grade is " + grades.Average().ToString("F1"));

You can combine an array of values into a comma separated string using the string.Join() function.

Console.WriteLine("I parsed these values: " + string.Join(",", grades));

So for example if the input is invalid you will see a 0 in place of the invalid value. Here is an example console output.

Enter grades separated by commas:
92,A,96,94
I parsed these values: 92,0,96,94
The average grade is 70.5

To convert the array of strings into an array of integers with one statement, use LINQ.

int[] grades = parts.Select((part) => int.Parse(part)).ToArray();

This will though an exception with invalid inputs. Making the above to work with TryParse() is tricker, but doable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Bruno
Solution 2