Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"System.FormatException" when getting user input from console - visual c#

I am trying to make a command line program that will ask if fast and long you want it to beep. I keep getting System.FormatException on the code below. I get the problem right after Console.WriteLine("how many times should i beep?");. I've found a fix by putting a console.read();//pause right after this line.

My question is what am I doing wrong? or am I suppose to have the pause after that line?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("how fast would you like the sounds to play?");
        Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
        string choice = Console.ReadLine();
        int speed = Convert.ToInt32(choice);
        Console.Write(speed);
        Console.Read();//pause
        Console.WriteLine("how many times should i beep?");
        string choice2 = Console.ReadLine();
        int j = Convert.ToInt32(choice2);
        Console.Write(j);
        Console.Read();//pause
        for (int i = 0 ; i < j; i++)
        {
            Console.Beep(1000, speed);
        }
    }
}
like image 860
hurnhu Avatar asked Jan 21 '26 00:01

hurnhu


1 Answers

My psychic debugging skills tell me that it's this line throwing the exception:

int j = Convert.ToInt32(choice2);

Putting the Console.Read() in like you mentioned before that causes that line not to execute immediately and delaying the throwing of the exception.

If you input something that isn't an integer on this line:

string choice2 = Console.ReadLine();

You will get a FormatException on the following Convert.ToInt32 call.

See the documentation for Convert.ToInt32 where it tells you a FormatException is thrown when the value you pass does not consist of an optional sign followed by a sequence of digits (0 through 9).

To solve your issue, use Int32.TryParse (or just make sure you enter a valid integer). That will return a boolean indicating the success or failure of the parsing rather than throwing an exception.

Also, welcome to StackOverflow! Be sure to upvote answers you find helpful and accept the one that best resolves your question.

like image 174
tnw Avatar answered Jan 22 '26 14:01

tnw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!