Is there a better than what I have done below to get an integer from the console?
I tried to write this so if the user enters anything 0 or less, or non-integer, the prompt keeps asking until it gets an integer.
Is there a different or better what than using the TRY and CATCH to reset max to 0 if it cant convert it to an int?

Thanks!

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

namespace Squares
{
    class Program
    {
        static void Main(string[] args)
        {
            int max;

            max = 0;

            while (max <= 0) {
                System.Console.Write("Enter the max number to calculate squares to: ");                   
                string i = System.Console.ReadLine();
                try 
                {
                    max = Convert.ToInt32(i);
                }
                catch
                {
                    max = 0;
                }
            }
        Console.WriteLine(max);
        }
    }
}

Recommended Answers

All 2 Replies

Rockpile,
TryParse Method

int n;
int.TryParse(Console.ReadLine(),  out n);

Much nicer, thanks adatapost. +rep

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.