I tried to Create a method to get value from the user then make a number generator of those values as a parameter but I Did not knew how !
//create a method that genereted the number of taple game
public void zahra()
{
Console.WriteLine("please enter value to random them betwen ");
Console.Write("from ");
ran = Convert.ToInt32(Console.ReadLine());
Console.Write("\n to ");
to = Convert.ToInt32(Console.ReadLine());
to++;
}
You could try:
// declare random instance outside of the method
// because we don't want duplicate numbers
static Random rnd = new Random();
public static int GenerateRandomNumber()
{
// declare variables to store range of number
int from, to;
// use while(true) and force user to enter valid numbers
while(true)
{
// we use TryParse in order to avoid FormatException and validate the input
bool a = int.TryParse(Console.ReadLine(), out from);
bool b = int.TryParse(Console.ReadLine(), out to);
// check values and ensure that 'to' is greater than 'from'
// otherwise we will get a ArgumentOutOfRangeException on rnd.Next
if(a && b && from < to) break; // if condition satisfies break the loop
// otherwise display a message and ask for input again
else Console.WriteLine("You have entered invalid numbers, please try again.");
}
// generate a random number and return it
return rnd.Next(from, to + 1);
}
You can add in the end of your script:
Random r=new Random();
Console.WriteLine(r.Next(ran, to));
of course you should declare ran
and to
as int.
edit:This is my whole project code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RND
{
class Program
{
static void Main(string[] args)
{
zahra();
}
public static void zahra()
{
Console.WriteLine("please enter value to random them betwen ");
Console.Write("from ");
int ran = Convert.ToInt32(Console.ReadLine());
Console.Write("\n to ");
int to = Convert.ToInt32(Console.ReadLine());
to++;
Random r=new Random();
Console.WriteLine(r.Next(ran, to));
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.