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);
}
}
}
Actually, all you need to do is remove those
Read()
pauses you threw in. I'd probably also change theWrite()
calls toWriteLine()
calls.You can also change the
Read()
calls toReadLine()
calls, if you insist on "pausing" there.why are those extra
Console.Read()
in there? They are breaking your program, because the user will pressreturn
too many timesTry this:
My psychic debugging skills tell me that it's this line throwing the exception:
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:
You will get a
FormatException
on the followingConvert.ToInt32
call.See the documentation for
Convert.ToInt32
where it tells you aFormatException
is thrown when the value you passdoes 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.