Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

try parse problem 2

Status
Not open for further replies.

Triacona

Technical User
Jun 11, 2009
462
0
0
GB
Hi all,
Great forum!![smile]
I have a problem with the following code:
Code:
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
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
 
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.
 
TryParse actually does the parsing; no need to parse the string a second time. Also, the result parameter needs to be specified as an [red]out[/red] parameter.

Code:
int result;
if (int.TryParse(p, [red]out[/red] result)) return result;
return -1; [green]// or whatever default value you want to return for an invalid result.[/green]
 
Shouldn't there be a default return of an integer in case the IF resolves to true?
 
Dear All,

Thank you for all your help [bigsmile]

I think I have it...
Code:
[COLOR=#729FCF]private static int[/color] readIntAns(string p)
        {
            [COLOR=#729FCF]int[/color] ans;
            Console.Write(p);
            if (([COLOR=#729FCF]int[/color].TryParse(Console.ReadLine(), out ans)== [COLOR=#729FCF]false[/color]))
            {
                [COLOR=#729FCF]return[/color] ans;
            }
            [COLOR=#729FCF]else[/color]
	        {
               [COLOR=#729FCF] return[/color] ans = 0;
	        }
        }[COLOR=#4E9A06]//end readIntAns[/color]
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:
 [COLOR=#729FCF]private static int[/color] readIntAns([COLOR=#729FCF]string[/color] p)
        {
            Console.Write(p);
            [COLOR=#729FCF]string[/color] ans = Console.Readline();
            [COLOR=#729FCF]return int[/color].Parse(ans);
         }[COLOR=#4E9A06]//end readIntAns[/color]

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

Thank you,

Kind regards

Triacona
 
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
 
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:
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:
private static int readIntAnswer(string question)
{
 int answer;
 Console.Write(question);
 int.TryParse(Console.ReadLine(), out answer);

 return answer;
}//end readIntAns

Bye, Olaf.
 
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:
  [COLOR=#729FCF]private static int[/color] readIntAns([COLOR=#729FCF]string[/color] p)
        {
            [COLOR=#729FCF]Console[/color].Write(p);
            [COLOR=#729FCF]if[/color] ((int.TryParse(Console.ReadLine(), out ans) == [COLOR=#729FCF]true[/color]))
            {
                [COLOR=#729FCF]return[/color] ans;
            }[COLOR=#4E9A06]//end if[/color]
            [COLOR=#729FCF]else[/color]
            {
                [COLOR=#729FCF]Console[/color].WriteLine("Invalid entry!! Please try again");
                [COLOR=#729FCF]Console[/color].WriteLine(p);
               [COLOR=#729FCF] if[/color] (([COLOR=#729FCF]int[/color].TryParse(Console.ReadLine(), [COLOR=#729FCF]out[/color] ans) == true))
                {
                    [COLOR=#729FCF]return[/color] ans;
                }[COLOR=#4E9A06]//end if[/color]
               [COLOR=#729FCF] else[/color]
                {
                    [COLOR=#729FCF]Console[/color].WriteLine("Invalid! Exiting to menu");
                    [COLOR=#729FCF]return[/color] ans = 5;
               }[COLOR=#4E9A06]//end else[/color]
             }[COLOR=#4E9A06]//end else[/color]
        }[COLOR=#4E9A06]//end readIntAns[/color]
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top