Reputation:
I'm still a beginner and I'm doing simple projects. The one I'm currently doing is a simple method that asks the user to enter a number 1-10. If they don't it'll keep asking till the requirement is met, then return the value. It doesn't though, please help.Thank you.
namespace Practice
{
class Program
{
static void Main(string[] args)
{
GetNumberFromUser();
Console.Read();
}
static int GetNumberFromUser()
{
int userNumber = 0;
while (userNumber < 1 || userNumber > 10)
{
Console.Write("Enter a number between 1 and 10: ");
string usersResponse = Console.ReadLine();
userNumber = Convert.ToInt32(usersResponse);
}
return userNumber;
}
}
}
Upvotes: 0
Views: 714
Reputation: 578
Try this. You have to print the value returned in console.
static void Main(string[] args)
{
var i = GetNumberFromUser();
Console.Write(i);
Console.Read();
}
static int GetNumberFromUser()
{
int userNumber = 0;
while (userNumber < 1 || userNumber > 10)
{
Console.Write("Enter a number between 1 and 10: ");
string usersResponse = Console.ReadLine();
userNumber = Convert.ToInt32(usersResponse);
}
return userNumber;
}
Upvotes: 1
Reputation: 156
You need to print the return value of the GetNumberFromUser() method in the main() method.
static void Main(string[] args)
{
Console.WriteLine(GetNumberFromUser());
Console.Read();
}
Upvotes: 2
Reputation: 280
Because you didn't print the integer out.
Why not using a int variable to store the return value of method GetNumberFromUser() and print the value?
You declared the return value of method GetNumberFromUser() is integer; If you don't want to return anything, just replace the
int
with
void
The method will be still executed once it's called.
static void Main(string[] args)
{
var res = GetNumberFromUser();
Console.WriteLine(res);
Console.ReadKey();
}
Upvotes: 0
Reputation: 2927
You need to assign the returned value to a variable from the method like this
static void Main(string[] args)
{
int input = GetNumberFromUser();
Console.Read();
}
After this you can use the input
variable according to your need
Upvotes: 1