Click here to Skip to main content
15,895,800 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want that if I write a string that it gives an error. How can I write that this code only take a numeric value.

C#
//This must be a numeric value

           Console.Write("Geef je startsalaris in: ");
           salaris = Convert.ToDouble(Console.ReadLine());
           while(//here should i say that if the user gives a string it will give this error)
           {
               Console.WriteLine("dit is geen numeriek waarde");
               Console.Write("Geef je startsalaris in: ");
               salaris = Convert.ToDouble(Console.ReadLine());
           }


What I have tried:

i have tried many things but without any solution.
Posted
Updated 19-Nov-16 1:03am

The TryParse function is specially designed for this type of operation.
C#
Console.Write("Geef je startsalaris in: ");
while(!double.TryParse(Console.ReadLine(), out salaris))
{
    Console.WriteLine("dit is geen numeriek waarde");
    Console.Write("Geef je startsalaris in: ");
}
 
Share this answer
 
Try this -

C#
double x = 0.0;
bool flag = true;

Console.WriteLine("Enter value : ");

while (flag)
{
    try
    {
        x = Convert.ToDouble(Console.ReadLine());
        flag = false;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Enter correct value :");
        flag = true;
    }
}

Console.WriteLine("ok :" + x);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900