How to incorporate some simple error checking

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 4807 Views - Last Post: 13 August 2007 - 01:10 PM Rate Topic: -----

#1 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

How to incorporate some simple error checking

Post icon  Posted 07 August 2007 - 04:01 PM

Okay I've got this cool simple program that asks the user to input two integers and then uses the comparison operators to perform some comparisons between them. The code works just fine, however I don't have any error checking built in yet, so if I was to enter like say the letter 's' the program would fail.

What I would really like to do is check to see if the value entered is in fact an integer, and if it's not an integer, show a message on the screen and keep looping until I do enter in an integer. So the screen will look like this:

Enter first integer: t
Sorry. You must enter an integer.
Enter first integer: s
Sorry. You must enter an integer.

I'm not familiar at all with error checking so this is kind of hard. Here is my program:

public static void Main()
	{
		int x = 0;
		int y = 0;

		try
		{
			Console.Write("Enter first integer: ");
			x = Convert.ToInt32(Console.ReadLine());

			Console.Write("Enter second integer: ");
			y = Convert.ToInt32(Console.ReadLine());
		}
		catch
		{
			

		}

		Console.WriteLine();

		if (x == y)
			Console.WriteLine("{0} == {1}", x, y);

		if (x != y)
			Console.WriteLine("{0} != {1}", x, y);

		if (x < y)
			Console.WriteLine("{0} < {1}", x, y);

		if (x > y)
			Console.WriteLine("{0} > {1}", x, y);

		if (x <= y)
			Console.WriteLine("{0} <= {1}", x, y);

		if (x >= y)
			Console.WriteLine("{0} >= {1}", x, y);

		Console.WriteLine();
	}



Is This A Good Question/Topic? 0
  • +

Replies To: How to incorporate some simple error checking

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 05:09 PM

357mag,

Try this, it first checks for a valid integer, if its not it alerts the user, otherwise it sets the 2 variables

public static void Main()
{
	int x = 0;
	int y = 0;

	try {
		Console.Write("Enter first integer: ");

		if (!int.TryParse(Console.ReadLine(), new int()))
		{
			Console.WriteLine("You must enter a numeric value");
			return;
		}
		else
		{
			x = Convert.ToInt32(Console.ReadLine());
		}

		Console.Write("Enter second integer: ");

		if (!int.TryParse(Console.ReadLine(), new int()))
		{
			Console.WriteLine("You must enter a numeric value");
			return;
		}
		else
		{
			y = Convert.ToInt32(Console.ReadLine());
		}
	}


	catch {
	}

	Console.WriteLine();

	if (x == y)
	{
		Console.WriteLine("{0} == {1}", x, y);
	}

	if (x != y)
	{
		Console.WriteLine("{0} != {1}", x, y);
	}

	if (x < y)
	{
		Console.WriteLine("{0} < {1}", x, y);
	}

	if (x > y)
	{
		Console.WriteLine("{0} > {1}", x, y);
	}

	if (x <= y)
	{
		Console.WriteLine("{0} <= {1}", x, y);
	}

	if (x >= y)
	{
		Console.WriteLine("{0} >= {1}", x, y);
	}

	Console.WriteLine();
}



Hope this helps :P

Happy Coding!
Was This Post Helpful? 0
  • +
  • -

#3 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 06:24 PM

Well I tried your suggestion but it's a no go. The compiler complains about the arguments. It says something about having some invalid arguments. It does not like the:
if (!int.TryParse(Console.ReadLine(), new int()))



Beats me. I don't know how to fix it.
Was This Post Helpful? 0
  • +
  • -

#4 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 06:32 PM

You're right, sometimes I get stuck in VB.Net Land, The New statement is whats bothering it, try this

public static void Main()
		{
			int x = 0;
			int y = 0;
			int myInt;

			try
			{
				Console.Write("Enter first integer: ");

				if (!int.TryParse(Console.ReadLine()))
				{
					Console.WriteLine("You must enter a numeric value");
					return;
					int.TryParse(Console.ReadLine,myInt);
				}
				else
				{
					x = Convert.ToInt32(Console.ReadLine());
				}

				Console.Write("Enter second integer: ");

				if (!int.TryParse(Console.ReadLine(), myInt))
				{
					Console.WriteLine("You must enter a numeric value");
					return;
				}
				else
				{
					y = Convert.ToInt32(Console.ReadLine());
				}
			}


			catch
			{
			}

			Console.WriteLine();

			if (x == y)
			{
				Console.WriteLine("{0} == {1}", x, y);
			}

			if (x != y)
			{
				Console.WriteLine("{0} != {1}", x, y);
			}

			if (x < y)
			{
				Console.WriteLine("{0} < {1}", x, y);
			}

			if (x > y)
			{
				Console.WriteLine("{0} > {1}", x, y);
			}

			if (x <= y)
			{
				Console.WriteLine("{0} <= {1}", x, y);
			}

			if (x >= y)
			{
				Console.WriteLine("{0} >= {1}", x, y);
			}

			Console.WriteLine();
		}


Was This Post Helpful? 0
  • +
  • -

#5 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 07:16 PM

No, that won't work either. You have to have another argument. I did this:

public static void Main()
	{
		int x = 0;
		int y = 0;

		try
		{
			Console.Write("Enter first integer: ");

			if (!int.TryParse(Console.ReadLine(), out x))
			{
				Console.Write("Sorry. You must enter a numeric value.");
			}
			else
				x = Convert.ToInt32(Console.ReadLine());
	   

			Console.Write("Enter second integer: ");

			if (!int.TryParse(Console.ReadLine(), out y))
			{
				Console.Write("Sorry. You must enter a numeric value.");
			}
			else
				y = Convert.ToInt32(Console.ReadLine());
			
		}
		catch
		{
		}



Now the program does compile. But unfortunately it does not work the way I want. Problem is when I see the first prompt and I enter the first integer, then I hit Enter to send it along, I don't see the prompt to enter the second integer. Instead, the blinking cursor moves to the next line and there is no text. Then lets say I do enter the second integer then and press Enter. Then I get the prompt to enter the second integer.

So the program is kind of goofed up.
Was This Post Helpful? 0
  • +
  • -

#6 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 08:18 PM

I'm just a little stumped here, but I think this is what you're looking for. The problem earlier is I had the if..else then nothing, I believe in the else I needed to set x then move onto getting y. I ran this on my computer and seen nothing wrong with it, let me know ok

public static void Main()
		{
			int x = 0;
			int y = 0;

			try
			{
				Console.Write("Enter first integer: ");

				if (!int.TryParse(Console.ReadLine(), out x))
				{
					Console.Write("Sorry. You must enter a numeric value.");
				}
				else
				{
					x = Convert.ToInt32(Console.ReadLine());
					Console.Write("Enter second integer: ");

					if (!int.TryParse(Console.ReadLine(), out y))
					{
						Console.Write("Sorry. You must enter a numeric value.");
					}
					else
						y = Convert.ToInt32(Console.ReadLine());
				}			   

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			Console.WriteLine();

			if (x == y)
			{
				Console.WriteLine("{0} == {1}", x, y);
			}

			if (x != y)
			{
				Console.WriteLine("{0} != {1}", x, y);
			}

			if (x < y)
			{
				Console.WriteLine("{0} < {1}", x, y);
			}

			if (x > y)
			{
				Console.WriteLine("{0} > {1}", x, y);
			}

			if (x <= y)
			{
				Console.WriteLine("{0} <= {1}", x, y);
			}

			if (x >= y)
			{
				Console.WriteLine("{0} >= {1}", x, y);
			}

			Console.WriteLine();		
		}


Was This Post Helpful? 0
  • +
  • -

#7 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 09:08 PM

No. It still doesn't work correctly. It compiles okay, but it does not run correctly at all. When I run the program and I get the first prompt, and then I enter in an integer like 12, and then I hit Enter, it's like the integer doesn't get sent to the program. The cursor moves to the next line with no text. Then I'll try to enter in the second integer, so I do, and then hit Enter, but then I get the second prompt to enter in the second integer.

Beats me. I thought your suggestion was going to work, but this may take awhile.
Was This Post Helpful? 0
  • +
  • -

#8 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4424
  • View blog
  • Posts: 12,293
  • Joined: 18-April 07

Re: How to incorporate some simple error checking

Posted 07 August 2007 - 11:10 PM

Well I can tell you the problem just looking at it.... you are readline() too many times. You need to write out the prompt, readline into x variable, prompt for second integer and readline into y variable. What is happening is during execution you are calling readline 4 times for two variables. Your first readline is inputing the value into x just fine. but then when it jumps to your else, you are readline() again to use in the convert.toint32. Why?

static void Main(string[] args)
{
			int x = 0;
			int y = 0;

			try {
				// Prompt for integer
				Console.Write("Enter first integer: ");
 
				// Read into the variable x and see if our parse was good.
				if (!int.TryParse(Console.ReadLine(), out x)) {
					Console.Write("Sorry. You must enter a numeric value.");
				}
				else {
					// Yes, first integer parsed ok. Prompt for second.
					Console.Write("Enter second integer: ");

					// Now lets parse second integer.
					if (!int.TryParse(Console.ReadLine(), out y)) {
						Console.Write("Sorry. You must enter a numeric value.");
					}
				}

			}
			catch (Exception ex) {
				Console.Write(ex.Message);
			}

			// We didn't hit our exception, so parses worked, now run our prints.
			Console.WriteLine();

			if (x == y) {
				Console.WriteLine("{0} == {1}", x, y);
			}

			if (x != y) {
				Console.WriteLine("{0} != {1}", x, y);
			}

			if (x < y) {
				Console.WriteLine("{0} < {1}", x, y);
			}

			if (x > y) {
				Console.WriteLine("{0} > {1}", x, y);
			}

			if (x <= y) {
				Console.WriteLine("{0} <= {1}", x, y);
			}

			if (x >= y) {
				Console.WriteLine("{0} >= {1}", x, y);
			}

			Console.WriteLine();		 
}



As you can see when you read the comments we bring in the values, parse them and test for success. Once we do this, the variable now contains the value (using the tryparse you are testing and inputting the value into the variable at the same time.)

P.S. If you are using VS 2005 you will want to start without debugging (ctrl + F5) so you can hold open the dos window long enough to see the results.

This should now work as you intended it to do. Enjoy!

This post has been edited by Martyr2: 07 August 2007 - 11:12 PM

Was This Post Helpful? 0
  • +
  • -

#9 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to incorporate some simple error checking

Posted 08 August 2007 - 04:29 AM

Thanks Marty2, it never even crossed my mind about the RealLine twice, sometimes I can be so blind/ignorant
Was This Post Helpful? 0
  • +
  • -

#10 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4424
  • View blog
  • Posts: 12,293
  • Joined: 18-April 07

Re: How to incorporate some simple error checking

Posted 08 August 2007 - 09:18 AM

It happens to all of us, that is why programmers can be great team players. If one doesn't catch it, others will. It is a good team environment here at DIC I must say. :)
Was This Post Helpful? 0
  • +
  • -

#11 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 08 August 2007 - 07:20 PM

Okay I'm going through my code writing some comments like I always do so I understand things. I'm trying to understand the int.TryParse(Console.ReadLine(), out x)part.

My understanding so far is that the first argument basically just represents the string(kind of the source)of what you are trying to convert. I'm okay so far. But now the second argument. According to the Deitel book, the keyword 'out' means tells the compiler that the argument will be passed
into the called method by reference and that the called method will assign a value to the original variable in the caller.

So if the TryParse( ) method returns True then the value of what I entered which is read into the method by Console.ReadLine( ) will be assigned to variable x by way of the out keyword. At least that's how I understand it. And if the method returns False well then we just go back to the top of the loop where we try again for a valid integer value.

But you see the Deitel book says "when you precede a parameter with keyword 'out' it tells the compiler that the argument will be passed into the called method by reference..."

It's a little confusing because it makes me almost think that the value entered is passed into the method through the keyword 'out'. But I don't think that is correct. I think the value is passed or read into the method through the Console.ReadLine( ) method, which is the first argument.

Am I correct?
Was This Post Helpful? 0
  • +
  • -

#12 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How to incorporate some simple error checking

Posted 08 August 2007 - 07:32 PM

The "out" parameter tells it to assign the value to the variable after the "out" if it passes the TryParse check.
Was This Post Helpful? 0
  • +
  • -

#13 graeme bradbury  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 28-June 07

Re: How to incorporate some simple error checking

Posted 09 August 2007 - 02:09 AM

In c# method parameters are either passed by reference or passed by value depending on their type. ie. Int32 is a value type so it's passed by value, String is a reference type so it's passed by reference.

Passing by reference means that the method gets a reference to the original object, so anything it does to the parameter is done to the original.

Passing by value means that the method gets a copy, so anything it does to the parameter doesn't affect the original.

"ref" and "out" both alter this behaviour of parameters by forcing value types to be boxed and passed by reference.

Where "out" and "ref" differ is in their requirements for the state of the paramter, "ref" requires that object is already initialized, whereas "out" will take an uninitialized object;

For example
int i;
someOutMethod(out i);

...

int a = 13;
someRefMethod(ref a);


Was This Post Helpful? 0
  • +
  • -

#14 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 11 August 2007 - 02:18 AM

I'm a little confused about the Logical NOT(!)operator. I thought that by reversing the condition it allows the statements in the body of the if structure to execute when the condition is false, but now I'm not so sure. I made this little test program for myself. Here it is:

 bool b = true;

			if (!b)
				Console.WriteLine("b is equal to true");
			else
				Console.WriteLine("b is equal to false");



When I run the program the line in the else clause runs, and I was expecting the line in the if part to run. Here is why I confused. I understand that the ! operator simply reverses the meaning of something. But let's look at the program I posted earlier. Look at the if statement:

if (!int.TryParse("Console.ReadLine( ), out x)
{
   Console.Write("Sorry. You must enter an integer.");
}



Okay. Notice the Logical NOT(!)operator in front of the int.TryParse method. My understanding of what is going on here is that if the TryParse method doesn't return a true result, then the statement in the body of the if will run.

Doesn't that basically mean that if the result is false, the statement in the body of the if will run?

If that's true here, how come it doesn't work in my little test example. When I went
if (!b)



The statement in the body of the if did not run, but instead the statement in the else clause ran instead.

How come with one example the statement in the body of the if will run, but in another example it will not, even though both times you are using the Logical NOT(!)operator?
Was This Post Helpful? 0
  • +
  • -

#15 357mag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 07-August 07

Re: How to incorporate some simple error checking

Posted 11 August 2007 - 03:11 AM

Maybe the way it's working is that if the TryParse( )method returns false, you can force the compiler to run the line of code that would normally only run when the condition is true in the body of the if statement, by using the Logical NOT operator in front of the condition or method. Like this:

bool b = false;

			if (!b)
				Console.WriteLine("Sorry. You must enter a value.");
			else
				Console.WriteLine("b is true");




Then what happens when the TryParse( )method returns True? Nothing? Is the Logical NOT operator just kind of ignored? Since there is no Else Clause the compiler simply assigns the value entered to the variable and we are done?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2