views:

365

answers:

4

I am creating a short c# console program that will ask 10 addition questions using random numbers from 0-10. Then it tells the user how many correct or incorrect. I am trying to find a way to validate that my user input is a number and not a letter. I am posting the code I have created so far, but could use some help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
      static void Main(string[] args)
      {            

         int i = 0;
         int input;
         int correct = 0;
         int incorrect = 0;
         int questions = 10;
         int[] solutions = new int[21];
         int[] answers = new int[21];
         int[] number1 = new int[21];
         int[] number2 = new int[21]; 

         Random number = new Random();

         Console.WriteLine("  This is a test of your basic addition skills. ");
         Console.WriteLine("  Please answer the random addition question below ");
         Console.WriteLine("  with a number from 1 - 20 and press enter to get the");
         Console.WriteLine("  next of 10 questions.  At the end of the questions");
         Console.WriteLine("  your results will be calculated and presented to you.");
         Console.WriteLine("");
         Console.WriteLine("");


         while (i < questions)
         {
            number1[i] = number.Next(0, 10);
            number2[i] = number.Next(0,10);
            solutions[i] = (number1[i] + number2[i]);

          //Console.WriteLine("{0} +  {1} =  {2}", number1[i], number2[i],solutions[i]);  


            Console.Write("  {0} +  {1} =  ", number1[i], number2[i]);


            answers[i] = Convert.ToInt32(Console.ReadLine()); // original code      

            //input = Convert.ToInt32(Console.ReadLine());
            //if (input > 0 && input <21)
            //{
            //   Console.WriteLine("YOur answer is: {0}", input);
            //}
            //else
            //Console.WriteLine("YOur answer is not valid");


            if (solutions[i] == answers[i])
            {
               Console.WriteLine("  Correct");
               correct++;
            }
            else
            {
               Console.WriteLine("  Your answer is incorrect, the correct answer is {0}", solutions[i]);
               incorrect++;

            }
            //Console.WriteLine("{0}", answers[i]);


            //int sum = numberone + numbertwo;
            //answers[sum]++;
            i++;
      }
         Console.WriteLine("");
         Console.WriteLine("");
         Console.WriteLine("The number correct is: {0}, The number incorrect is: {1}", correct, incorrect);
      }
      }
   }
+14  A: 

Use int.TryParse() like:

bool isNumber=false;
int number;
while (!isNumber)
{
  string txt = Console.ReadLine();
  if (!int.TryParse(txt, out number))
  {
    // not a number, handle it
    Console.WriteLine("This is not a number, enter a number. For real now.");
  }
  else
  {
    // use number
    answers[i] = number;
    isNumber = true;
  }
}
Wim Hollebrandse
nice and direct, no extra exceptions floating around
curtisk
Why not just use Int32.TryParse(String, Int32) instead of doing it twice?
Philip Wallace
Yes, Xaero. Edited to reflect the right overload.
Wim Hollebrandse
need an out parameter - won't compileand int number will only be accessible from inside the else scope
PostMan
It just left blank positions in the answers array
eKek0
Oh you fixed it :)
PostMan
+2  A: 
int iResult = int.MinValue;
bool bParsed = int.TryParse("xyz", out iResult);

TryParse will not throw an exception.

However, you can use Convert.ToInt32() as well if needed but that will throw an exception on bad data.

AboutDev
No need to initialize iResult as it is an out parameter.
Philip Wallace
A: 

This allows you to fill all positions of your array:

int result;
bool isInt = Int32.TryParse(Console.ReadLine(), out result);
if (!isInt) {
  Console.WriteLine("Your input is not an integer number.");
  continue;
}

answers[i] = result;
eKek0
Why the 'continue'?
Philip Wallace
I also want to prompt the user to reenter a number
Eric
Eric, simply put a while (validNumber) around the ReadLine with a boolean flag 'validNumber' which you set to true if valid, and to false outside of the while loop.
Wim Hollebrandse
+3  A: 

Instead of:

answers[i] = Convert.ToInt32(Console.ReadLine()); // original code

Use:

int input;
bool validInput = int.TryParse(Console.ReadLine(), out input);
if (!validInput || input < 0 && input > 20)
    <throw exception or display some error message here...>

EDIT: If you want to recursively ask for a correct input, this is how you can do it:

int input;
bool validInput = false;

while (!validInput)
{
    validInput = int.TryParse(Console.ReadLine(), out input);
    if (!validInput || input < 0 && input > 20)
    {
     validInput = false; // We need to set this again to false if the input is not between 0 & 20!
     Console.WriteLine("Please enter a number between 0 and 20");
    }
}
Yogesh
Working with your solution, but I also want to reprompt the user to reenter a valid answer, should I use a while loop instead of an if? and can I do that?
Eric
Check my edited post. Added the answer to it.
Yogesh