0

I'm trying to make it so that when a number is entered my program will not crash, which this does so far. Then I want it to re ask for an input until the correct charcter type is enetered.

int firstNum;
int Operation = 0;

   switch(Operation)
   {
        case 1:
            bool firstNumBool = int.TryParse(Console.ReadLine(), out firstNum);
         break;
   }
2
  • 2
    You would need to wrap your logic in a loop, I would suggest a while loop on each execution of the loop, check if the Console.ReadLine() value is equal to the character and if so, terminate the loop Commented Nov 14, 2018 at 13:29
  • @RyanWilson I get I need some sort of loop but idk how to code it, like while (firstNum != int) { int.tryparse(Console.readline())? Commented Nov 14, 2018 at 13:31

1 Answer 1

2

Decompose your solution; extract a method for inputing an integer:

 private static int ReadInteger(string title) {
   // Keep on asking until correct input is provided
   while (true) {
     if (!string.IsNullOrWhiteSpace(title))
       Console.WriteLine(title);

     if (int.TryParse(Console.ReadLine(), out int result))
       return result;

     Console.WriteLine("Sorry, not a valid integer value; please, try again.");
   }
 }

And then use it:

 int firstNum;

 ...

 switch(Operation)
 {
      case 1:
          firstNum = ReadInteger("First number");
          break;

      ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.