Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Basics (Retired) Perfect Final

FormatException

i have this err. and i dont know how to fix it. pls help me System.ArgumentNullException: Value cannot be null. Parameter name: String at System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) [0x00054] in /builddir/build/BUILD/mono-4.8.1/mcs/class/referencesource/mscorlib/system/number.cs:1074 at System.Number.ParseInt32 (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) [0x00014] in /builddir/build/BUILD/mono-4.8.1/mcs/class/referencesource/mscorlib/system/number.cs:745 at System.Int32.Parse (System.String s) [0x00000] in /builddir/build/BUILD/mono-4.8.1/mcs/class/referencesource/mscorlib/system/int32.cs:120 at Treehouse.CodeChallenges.Program.Main () [0x00011] in <63c0b697f8714d7dadfbc9d3af622980>:0 at MonoTester.Run () [0x00208] in /workdir/MonoTester.cs:140

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            int i = 0;
            while(true)
            try {
                    Console.Write("Enter the number of times to print \"Yay!\": ");
                    int number = int.Parse(Console.ReadLine());
                    while (i < number)
                    { Console.WriteLine("\"Yay!\""); i++; }
                    break;

                }

            catch(FormatException) { Console.WriteLine("You must enter a whole number.");continue; }

        }
    }
}

2 Answers

Richard Schwind
Richard Schwind
1,785 Points

Try using:

int number = Convert.ToInt32(Console.ReadLine());

Instead of:

int number = int.Parse(Console.ReadLine());

int.Parse() throws an ArgumentNullException when it is passed a null argument. However, Convert.ToInt32() returns 0 when it is passed a null argument. For a more in-depth explanation on how these two methods work, check out this discussion on StackOverflow.

oh i see, thank you so much ^^