I'm still a beginner to programming in high-level programming languages, so I don't know if this is an easy solution, but I'm happy to learn anyway. I've programmed a little alarm program in C# that let's the user input in how many seconds the alarm needs to go off. It works perfectly, but the input that the user needs to give has to be a number. When the user inputs any form of text, the program crashes. Now, how can I prevent that users input text, and call a function or do something else when the user does, instead of the program just crashing?
This is the code I have now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Alarm
{
public static void play()
{
int sec;
sec = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i < seconds; ++i)
{
System.Threading.Thread.Sleep(1000);
}
for (int i = 0; i < 10; i++)
{
Console.Beep();
}
}
}
}
To prevent user from typing in text field without disabling the field with HTML, we can add the readonly attribute to the input. to stop users from enter text into the input without making it look disabled.
The onpaste attribute lets us prevent pasting into the form. Adding the autocomplete attribute as well as preventing drag and drop into the element. If you want to avoid the on{event} code in the HTML, you can do it the cleaner way: myElement.
You should complete a check before converting:
int sec;
if (int.TryParse(Console.ReadLine(), out sec)
{
// this is valid continue
}
else
{
// show error highlighting that entry must be a number
}
int.TryParse
will return a boolean highlighting whether the input is parsable to an int. It will also set your sec
variable to the value if successful.
You could loop indefinitely until the user inputs a number:
int number = 0;
while(!Int32.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Please input a number.");
}
Int32.TryParse
returns false
if the conversion failed, instead of throwing an exception and if successful returns the result in the second out
parameter.
Already people answered here.
I love to make that as an extension method
so that i can call it in so many places.
public static bool IsNumeric(this string theValue)
{
long retNum;
return long.TryParse(theValue, System.Globalization.NumberStyles.Integer,
System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
}
Then I will call it like this
if(Console.ReadLine().IsNumeric())
{
//The value is numeric. You can use it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With