-5
private int scanner = Convert.ToInt32(Console.ReadLine());
public void Play()
        {
            while (true)
            {
                if (scanner > theNumber)
                {
                    Console.WriteLine("your number is too big");
                } else 
                if (scanner < theNumber)
                {
                    Console.WriteLine("your number is too big");
                }  else
                {
                    Console.WriteLine("you got it");
                    break;
                }
            }
        }

this is a simple game where I need to iterate thr same number through the set of if statements. in Java they use

int x;

x = scn.nextInt();

What can I use in C#? There is no scanner.

C# equivalent to Java's scn.nextInt( ) this post doesn't explain how to make a scanner in C#. It only explains how to parse user's input so that make it Integer only

feedthemachine
  • 592
  • 2
  • 11
  • 29
  • `Convert.ToInt32` can raise an exception depending on what does the user input. `Int32.TryParse` is a better choice. – Cleptus Jul 19 '19 at 08:55
  • [C# equivalent to Java's scn.nextInt( )](https://stackoverflow.com/questions/23856969/c-sharp-equivalent-to-javas-scn-nextint) – xdtTransform Jul 19 '19 at 08:56
  • If you really need the Java like Scanner, you can port the https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/Scanner.java . The C# conversion should be really straightforward. – xdtTransform Jul 19 '19 at 09:00

1 Answers1

1

Let's extract a method (ReadInteger) for it. Please, note, that we use int.TryParse instead of Convert.ToInt32 since user input is not necessary a valid integer

 private static int ReadInteger(String title = null) 
 {
     if (!string.IsNullOrWhiteSpace(title))
         Console.WriteLine(title);

     while (true) 
     {
         if (int.TryParse(Console.ReadLine(), out int result))
             return result;

         Console.WriteLine("Sorry, the input is not a valid integer, try again");
      } 
 }

Then we can use it:

    public void Play()
    {
        while (true)
        {
            // We should re-read value after each attempt
            int value = ReadInteger();

            if (value > theNumber)
            {
                Console.WriteLine("your number is too big");
            } 
            else if (value < theNumber)
            {
                Console.WriteLine("your number is too big");
            }  
            else
            {
                Console.WriteLine("you got it");
                break;
            }
        }
    }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215