Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to use the if..else statement to only accept positive integers without needing catch(formatException)

What I have tried:

//ExceptionHandling.cs
//write a program not catching every exception
using System;

class ExceptionHandling
{
    static void Main(string[] args)
    {
      
        bool continueLoop = true;
        
        do
        {
            try
            {
                Console.WriteLine("Enter the first integer to add:");
                int a = Int32.Parse(Console.ReadLine());
                Console.WriteLine("Enter second integer to add:");
                int b = Int32.Parse(Console.ReadLine());
                int sum = a + b;

               if(a < 0)
                {
                    Console.WriteLine("Please enter a non-negative integer:", a);
                    Console.ReadLine();
                } 
                if (b < 0)
                {
                    Console.WriteLine("\nPlease enter a non-negative integer:", b);
                    Console.ReadLine();

                }
                      
               
                
                    
                    Console.WriteLine("\nTotal is {0}", sum);
                continueLoop = false;

            }//end try

            catch (FormatException formatException)
            {
                Console.WriteLine("\n" + formatException.Message);
                Console.WriteLine("Please enter an integer and try again. \n");

            }//end catch
        }
        while (continueLoop);   //end do-while


        Console.WriteLine("\nPress enter to exit.");
        Console.ReadLine();
    }
}
Posted
Updated 24-Jan-17 18:25pm
v3
Comments
[no name] 24-Jan-17 15:50pm    
Use TryParse
Philippe Mori 25-Jan-17 12:26pm    
Do you really want to ask both numbers again if one is negative?

public int GetValue(string prompt)
   {
   int value;
   while (true)
      {
      Console.WriteLine(prompt);
      if (int.TryParse(Console.ReadLine, out value))
         {
         break;
         }
      }
   return value;
   }
 
Share this answer
 
Comments
Philippe Mori 25-Jan-17 12:23pm    
Validation is missing to ensure positive number...
Try this:
using System;

public class Program
{
	public static void Main()
	{
		int input;
		bool isInteger = false;
		do
		{
			Console.WriteLine("Input a positive integer:");
			isInteger = Int32.TryParse(Console.ReadLine(), out input);
		}
		while (!(isInteger && input >= 0));
		Console.WriteLine("You have input " + input);
	}
}
 
Share this answer
 
Comments
Philippe Mori 25-Jan-17 12:24pm    
Should be a function as in solution 2...
OfficialSub0 25-Jan-17 14:02pm    
Enter the first integer to add:
-2
Enter second integer to add:
5
Input a positive integer:
2345677
You have input 2345677

Total is 3

Press enter to exit.

This is the output in the command prompt. Sorry if i didn't clarify, but I do indeed want to keep formatException to catch any input that's not an integer (ex:"hello").
Philippe Mori 25-Jan-17 14:08pm    
If you use your original code and both solutions 2 and 3, then it is trivial to solve your problem... If you expect us to give a complete solution, then you won't learn much and not improve yourself.
OfficialSub0 25-Jan-17 15:57pm    
Thanks I understand that part now! If I may ask, does the TryParse method allow for use of formatException because it skips it?

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