View Single Post
  #2 (permalink)  
Old 03-31-2008, 12:37 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,834
Last Blog:
Web slideshow in JavaS...
Rep Power: 78
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Wink Re: Question about C# user int input

By default, Console.ReadLine() returns a string value, regardless of what the user types. However, you can convert this to a string using the "int" object itself:
Code:
int x = int.Parse(Console.ReadLine());
 Console.WriteLine("you just wrote {0}", x);
Be careful, though. What if the user types something other than a number into the command prompt? In this case, you can use TryParse() to test if the line is a number:

Code:
string line = Console.ReadLine();
if (int.TryParse(line))
{
   int x = int.Parse(Console.ReadLine());
   Console.WriteLine("you just wrote {0}", x);
}
else
{
   Console.WriteLine("You didn't enter a number.")
}
The problem with this is that it will not keep asking for the piece of info. Consider this:

Code:
Console.WriteLine("Please enter your age:");
string line = Console.ReadLine()

while (!int.TryParse(line))
{
Console.WriteLine("This is not a valid number. Please enter again:");
line = Console.ReadLine();
}

int x = int.Parse(line);
Console.WriteLine("you just wrote {0}", x);
In this case, we use a "while" loop. If the user doesn't enter a valid number, the program asks for it again, until the user does enter an age. You might want to put an "if" statement in, to test whether or not the user wants to cancel.

Hope this helps,

Xav
Reply With Quote