Home > database >  How to make an exception if input is not digit
How to make an exception if input is not digit

Time:12-20

How can I make and exception if input from Console.ReadLine is not digit?

    while (price != -1)
    {
        
        subtotal = subtotal   price;
        Console.Write("Value: [-1 to exit]");
        price = Convert.ToDouble(Console.ReadLine());      
        
    }

CodePudding user response:

That is why TryParse has been designed: instead of converting, having format exception, catching them etc.

price = Convert.ToDouble(Console.ReadLine()); 

you can put

while (!double.TryParse(Console.ReadLine(), out price))
  Console.WriteLine("Syntax error. Please, try again. Value: [-1 to exit]");

// from now on, price is a valid double

Code:

while (price != -1) {
  subtotal = subtotal   price;
  Console.Write("Value: [-1 to exit]");
  
  while (!double.TryParse(Console.ReadLine(), out price))
    Console.WriteLine("Syntax error. Please, try again. Value: [-1 to exit]");
}

CodePudding user response:

For things like this I usually recommend that you make a method that asks a question and gives back an answer, or repeats the question if the input is invalid:

private double AskDouble(string question){
  double result = 0;
  do {
    Console.Write(question);
  } while (!double.TryParse(Console.ReadLine(), out result))
  return result;
}

You can then neatly use this for multiple times where you need a number:

double weight = AskDouble("Enter your weight in kg: ");
double height = AskDouble("Enter your height in m: ");
double age = AskDouble("Enter your age in years: ");
  •  Tags:  
  • c#
  • Related