Home > Software engineering >  Noob is making a randomizer in C#
Noob is making a randomizer in C#

Time:05-28

I am studying c# and want to make a randomizer. But I faced with a problem, that the second variable is taked as 0(or something else idk)enter image description here It was after inputing the first variable

class RandomGenerator
{
    static void Main()
    {
        Random count = new Random();
        int a = Console.Read();
        int b = Console.Read();
        int randm = count.Next(a, b);
        Console.WriteLine(randm);
    }
}

CodePudding user response:

I don't think, that Console.Read() is suitable for your case. It's better to use Console.ReadLine()

Random count = new Random();
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int randm = count.Next(a, b);
Console.WriteLine(randm);

CodePudding user response:

To explain why everyone is raising issue with you using Console.Read you have to understand some stuff that is fairly obscure:

  • ints and chars in c# are fairly interchangeable. You can say int x = '0' and x ends up as 48. The char zero is at position 48 in the ascii table, though it's easier to remember in hex at position 0x30. Char 1 is as 0x31 and so on
  • Console.Read() returns a single char from the console input stream. When you type in the console you can put multiple chars in at once and each time you call Read() one of them is read

So you've been doing Read and stashing it in an int. say you put 7 into your app for the first value then presses Enter to get it to do something

The 7 character is read into a as 0x37 or 55 in decimal terms so a is 55. Because you pressed enter to get the app to do something the very next chars in the input buffer are a char 13 (a carriage return) and a char 10 (a newline)

The second call to read reads the carriage return into b, so b ends up as the number 13

Your attempt to get a random number this calls Next with a min of 55 and a max of 13.

This causes it to throw an exception

The other answer works better because ReadLine reads all the input til it encounters a char13/char10 pair and then returns the data without that trailing new lines pair. This means a string of eg "7" would be returned and this is int parsed to the he number 7

  • Related