INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

try parse problem

try parse problem

(OP)
Hi all,
Great forum!!smile
I have a problem with the following code:

CODE --> c#

private static int readIntAns(string p)
        {
            string ans;
          
                Console.Write(p);
                ans = Console.ReadLine();
                if ((int.TryParse(ans,ans) == false))
                {
                    ans = "";
                }
                else
                {
                    return int.Parse(ans);
                }

        }//end readIntAns 

Quote:

Argument2: cannot convert from string to out int
The best overloaded method match for int.TryParse(string, out) has some invalid arguments

Please help this is a bit of a headbanger [pc]
Thank you bigsmile

Thank you,

Kind regards

Triacona

RE: try parse problem

1.) Any specific reason why you are not working with p directly?
2.) TryParse expects an int as second parameter, so this should do it:

CODE

int result=0;    
                if (int.TryParse(p,result))
                {
                    result = int.Parse(p);
                }
return result; 

OK?

Cheers,
MakeItSo

“Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family.” (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.

RE: try parse problem

TryParse actually does the parsing; no need to parse the string a second time. Also, the result parameter needs to be specified as an out parameter.

CODE

int result;
if (int.TryParse(p, out result)) return result;
return -1; // or whatever default value you want to return for an invalid result. 

RE: try parse problem

Shouldn't there be a default return of an integer in case the IF resolves to true?

RE: try parse problem

(OP)
Dear All,

Thank you for all your help bigsmile

I think I have it...

CODE

private static int readIntAns(string p)
        {
            int ans;
            Console.Write(p);
            if ((int.TryParse(Console.ReadLine(), out ans)== false))
            {
                return ans;
            }
            else
	        {
                return ans = 0;
	        }
        }//end readIntAns 
this works for what I want it to do.
the method takes in a string parameter, the

CODE

ans = readIntAns("Please enter your choice: "); 
so writes to screen Please enter your choice:
then the user enters their choice and we read it via a Console.Readline();
assign it to ans and then output ans if it is an int.

The original code looked like this; btw this is a console app

CODE

private static int readIntAns(string p)
        {
            Console.Write(p);
            string ans = Console.Readline();
            return int.Parse(ans);
         }//end readIntAns 

If I'm getting this concept wrong please correct me.
Thanks smile

Thank you,

Kind regards

Triacona

RE: try parse problem

(OP)
Below seems to work, changed false to true otherwise returned 0
private static int readIntAns(string p)
{
int ans;
Console.Write(p);
if ((int.TryParse(Console.ReadLine(), out ans)== true))
{
return ans;
}
else
{
return ans = 0;
}
}//end readIntAns

Thank you,

Kind regards

Triacona

RE: try parse problem

Just two things:

1. Be more verbose, don't abbreviate things just to save a little typing, intellisense will help you type effective also with longer method and variable names and this helps in the direction of maintainability, documentation in making code more easy to read.
2. if (booleanexpression == true) can be written shorter as IF (booleanexpression), no need to compare with true. If the bolean expression wouldn't result in a boolean type the compiler will error.
Also if (booleanexpression == false) can be written as if (!booleanexpression)
3. As a good practice I would only make one return, where possible, all other code should only prepare the variable or value to be returned, so rewrite your last code to. If you code this way all the way you always have it easy to see what a function returns.

Putting both together I would put return ans; at then end. And so the if in your code wouldn't need to do anything in the if branch, only the else branch would be relevant.

CODE --> C#

private static int readIntegerAnswer(string question)
{
 int answer;
 Console.Write(question);
 if (!(int.TryParse(Console.ReadLine(), out answer))
 {
  answer = 0;
 }
 return answer;
}//end readIntAns 

Next step:

4. TryParse already sets the output parameter to 0, if the parsing of the input string fails, so there even is no need for answer=0. Even if Tryparse wouldn't do that, 0 is the default value of new int variables. So actually you set answer to 0 three times in case the user doesn't enter 1,2,3...

So the code shortens to:

CODE --> C#

private static int readIntAnswer(string question)
{
 int answer;
 Console.Write(question);
 int.TryParse(Console.ReadLine(), out answer);

 return answer;
}//end readIntAns 

Bye, Olaf.

RE: try parse problem

(OP)
Thanks for all your help I will take it on board,
I have a setting to turn ans into 5 as this returns the user to the main menu.
see below

CODE

private static int readIntAns(string p)
        {
            Console.Write(p);
            if ((int.TryParse(Console.ReadLine(), out ans) == true))
            {
                return ans;
            }//end if
            else
            {
                Console.WriteLine("Invalid entry!! Please try again");
                Console.WriteLine(p);
                if ((int.TryParse(Console.ReadLine(), out ans) == true))
                {
                    return ans;
                }//end if
                else
                {
                    Console.WriteLine("Invalid! Exiting to menu");
                    return ans = 5;
               }//end else
             }//end else
        }//end readIntAns 
with the following menu:

CODE

private static void Menu()
        {

                Console.Clear();
                Console.WriteLine("=======================");
                Console.WriteLine("This program performs 3 calculations");
                Console.WriteLine("Please choose from 1-4");
                Console.WriteLine("1: Calculate Distance from -1,-1 to your choice");
                Console.WriteLine("2: Calculate the area of a circle using radius");
                Console.WriteLine("3: Display months of the year");
                Console.WriteLine("4: Exit");
                Console.WriteLine("=======================");
                ans = readIntAns("Please enter your choice: ");
                switch (ans)
                {
                    case 1:
                        calcDistance();
                        break;
                    case 2:
                        calcCircleArea();
                        break;
                    case 3:
                        displayAllMonths();
                        break;
                    case 4:
                        break;
                    case 5:
                        Menu();
                        break;
                    default:
                        break;
                }//end switch
                

        }//end Menu() 

I will try implement what you have said and make it simpler and more readable.
Thanks smile

Thank you,

Kind regards

Triacona

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close