When I try to enter the quit string, xxx, why does it throw an exception? It works in a while loop, but not with do…while loop.
After I convert to integer, the string variable only lets me use numeric characters (like -999) to exit the do…while loop. But I want to make the loop control variable a word like “quit” and not numbers. How can I do that?
Here is my code.
using System;
namespace StringInputPractice
{
class StringInputPractice
{
static void Main()
{
// Declarations
string inValue;
int first;
int second;
int sum;
do
{
Console.Write("\nEnter the first number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
first = Convert.ToInt32(inValue); //@@@@@
Console.Write("\nEnter the second number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
second = int.Parse(inValue);
sum = first + second;
Console.WriteLine("\nThe sum of {0} and {1} is {2}.", first,
second, sum);
/* Things I've tried inside do { } and that don't work */
//inValue = "";
//inValue = null;
//inValue = inValue.ToString();
//inValue = first.ToString();
//inValue = second.ToString();
}
while (inValue != "xxx"); /*If you enter a non-numeric string,
* an exception is thrown at
* @@@@@ above.
*/
Console.ReadLine();
}
}
}
Try this: use int.TryParse instead of
Convert.ToInt32