Reputation: 17
I am learning how to program so please be nice. :)
I have this error running the code:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.
When I type "screw you, don't tell me what to do!". When I delete the whole insult part of the code, it's working flawlessly. What am I doing wrong?
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int numero1 = 5; //Declaring first variable
int numero2 = 5; //Declaring second variable
Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2); //Asking question to the user
int answer = Convert.ToInt32(Console.ReadLine()); //Converting the "answer" to integral variable
string insult = Console.ReadLine(); //The user enter his insult
if (answer == 25) //If the answer is 25
{
Console.WriteLine("Good answer!"); //This message appears
}
else if (insult == "screw you, don't tell me what to do!") //If the user insult me
{
Console.WriteLine("Wow buddy, gotta check that language!"); //The user receives this message
}
else
{
Console.WriteLine("Dude...what?"); //If the user write anything else, he gets this message
}
Console.ReadKey();
}
}
}
Upvotes: 0
Views: 100
Reputation: 66
Do like this:
int numero1 = 5; //Declaring first variable
int numero2 = 5; //Declaring second variable
Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2); //Asking question to the user
string answer = Console.ReadLine(); //Converting the "answer" to integral variable
if (answer == "25") //If the answer is 25
{
Console.WriteLine("Good answer!"); //This message appears
}
else if (answer == "screw you, don't tell me what to do!") //If the user insult me
{
Console.WriteLine("Wow buddy, gotta check that language!"); //The user receives this message
}
else
{
Console.WriteLine("Dude...what?"); //If the user write anything else, he gets this message
}
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
This is a simple change that makes your code easier to understand, hopefully. You are already "hardcoding" the results so by putting 25, in a string, does not make your code less good.
Upvotes: 1
Reputation: 63065
use int.TryParse
as below, if user enter non integer value your program will fail
Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2);
string keyboardInput = Console.ReadLine();
int answer;
while (!int.TryParse(keyboardInput, out answer)) {
Console.WriteLine("Invalid input, try again.");
keyboardInput = Console.ReadLine();
}
// now read the insult
string insult = Console.ReadLine();
since you need two inputs you need to click enter after entering answer, then again you can type the insult and hit enter
Upvotes: 0