Skip to main content
gamedev.net
🔒 Locked

Exception checking?

Started by alvarofrank Jul 28, 2007 at 6:59 PM 5 replies 1.2k views
Original Post
alvarofrank
alvarofrank
Hi all, i have been working on project1, but i cant get my code to verify if the user input is of the correct type, help will be appreciated.
 using System;
using System.Collections.Generic;
using System.Text;

namespace maze
{
    
    class Program
    {
        public class Settings
        {
            public void RowSettings()
            {
                int Rows;
                string Temp;
                int Temp2;

                Console.WriteLine("Please enter the number of rows between 2-50:");
                Temp = Console.ReadLine();
                Console.WriteLine("You chose {0} rows", Temp);
                Temp2 = int.Parse(Temp);
                if (Temp2 >= 2 && Temp2 <= 50)
                    Rows = Temp2;
                else
                    RowSettings();

            }
        }

        static void Main(string[] args)
        {            
            Console.WriteLine("Random Maze Generator by Yolda!");
            Settings Settings = new Settings();
            Settings.RowSettings();

        }
    }
}

popcorn
popcorn
What do you mean verify if the user input is of the correct type, if the user does not type in a number(i.e something like "abcd" then from what I have read int.Parse() throws an exception. int.Parse only works ok if the string entered can be converted to a integer.

I personally would not create a class to do something like this alvarofrank, a function would be preferable, it looks like you are calling the RowSettings method recursively if the input is not correct but I think this is too complicated.

I think a function and either a while or a do-while loop is all that would be needed to get the row and column data.

If this is about exception handling then I think you need to enclose the int.Parse() in a try/catch block but I don't really understand exceptions and their uses very well. Theres also a TryParse() method which you might want to use instead which returns a bool to indicate whether the parse was successful or not.
How about them apples?
alvarofrank
alvarofrank
i mean, how can i assure that the users input is not a string without having an exception ending my program? The loop can be done in many ways, with whiles or a recursive structure, thats no issue for me, but i cant figure out how to manage the user input. i can guess using a "is?" or something command like that, but i dont know how to use them.
popcorn
popcorn
I just added something to my original post about using the try/catch block but from what I have seen the int.TryParse method looks to be the best way to go about it, so I imagine something like:

if(int.TryParse(Temp, Temp2))
{
//set the row info
}
else
System.Console.WriteLine("Invalid input");
How about them apples?
Spoonbender
Spoonbender
Quote:
Original post by alvarofrank
i mean, how can i assure that the users input is not a string without having an exception ending my program?

You can catch the exception that is thrown:
try {    string myInputString; // Assume this holds the input from the player    int result = int.Parse(myInputString);    Console.WriteLine("Hurrah, your input turned out to be a valid integer");}catch {    Console.WriteLine("Oops, that's not an integer. Good thing I can handle exceptions, or you would have crashed my program!");}


As suggested above, you can also use int.TryParse instead, which doesn't throw an exception, but simply returns false if it failed to parse the string.
jwwicks
jwwicks
Quote:
Original post by alvarofrank
Hi all, i have been working on project1, but i cant get my code to verify if the user input is of the correct type, help will be appreciated.
*** Source Snippet Removed ***


I used something like the following...
using System;using System.Text.RegularExpressions;namespace Game{	/// <summary>	/// Main Application Class for Game.	/// </summary>	class App	{		/// <summary>		/// The main entry point for the application.		/// </summary>		[STAThread]		static int Main(string[] args)		{			int ret_val = 0;			sbyte rowSize = 0;			sbyte colSize = 0;			do			{				ShowAppInfo( "My Maze Factory", "0.99.00");				GetMazeDimension( ref rowSize, "Rows (height)", 2, 50 );				GetMazeDimension( ref colSize, "Columns (width)", 2, 50 );			}while( !IsAppDone() );			return ret_val;		}		static void ShowAppInfo( string AppName, string Version )		{			Console.WriteLine("{0} - {1}\n\n", AppName, Version);		}		static bool IsAppDone()		{			bool ret_val = false;			string answer;					do			{				Console.Write("Would you like to display another Maze: ");				answer = Console.ReadLine();			}while( !IsValidAnswer( answer) );			if( Regex.IsMatch(answer, @"^[Nn]$|^[Nn][Oo]$") )				ret_val = true;			return ret_val;		}		static void GetMazeDimension( ref sbyte Size, string Dim, sbyte Min, sbyte Max )		{			do			{				Console.Write("Number of {0} in Maze ( {1} to {2} ): ", Dim, Min, Max);				try				{					Size = SByte.Parse(Console.ReadLine());				}				catch( Exception e )				{					Console.WriteLine("Error: Please enter a number from {0} to {1} !", Min, Max);				}			}while( !IsValidSize( Size, Min, Max ) );		}		static bool IsValidAnswer( string s )		{			bool ret_val = false;			ret_val = Regex.IsMatch( s , @"^[Nn]$|^[Nn][Oo]$|^[Yy]$|^[Yy][Ee][Ss]$");			if (!ret_val)				Console.WriteLine("Please enter either y[es] or n[o]...");			return ret_val;		}		static bool IsValidSize( sbyte Val, sbyte Min, sbyte Max )		{			bool ret_val = false;			if( Val < Min | Val > Max )				Console.WriteLine("Error: Value must be from {0} to {1}.", Min, Max);			else				ret_val = true;						return ret_val;		}	}}


JW
Computers are useless, they can only give you answers. - Pablo Picasso

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.