-1

My background is java and I'm learning some C# Programming language code.

My Question is: Java has an Scanner class for taking integer input from the user is there something similar in C#

example: Java

    import java.util.Scanner;


    class myClass{

    myClass{

    }

        public static void main(){
        //Scanner object

        Scanner input = new Scanner(System.in)
        input.nextInt();
    }
}

anything similar in C#

2 Answers2

1

Yes, there is Console.ReadLine.

https://docs.microsoft.com/en-us/dotnet/api/system.console.readline?redirectedfrom=MSDN&view=netframework-4.7.2#System_Console_ReadLine

Or, you can create your own Scanner class in C# Stolen from Is there an equivalent to the Scanner class in C# for strings?

class Scanner : System.IO.StringReader
{
  string currentWord;

  public Scanner(string source) : base(source)
  {
     readNextWord();
  }

  private void readNextWord()
  {
     System.Text.StringBuilder sb = new StringBuilder();
     char nextChar;
     int next;
     do
     {
        next = this.Read();
        if (next < 0)
           break;
        nextChar = (char)next;
        if (char.IsWhiteSpace(nextChar))
           break;
        sb.Append(nextChar);
     } while (true);
     while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
        this.Read();
     if (sb.Length > 0)
        currentWord = sb.ToString();
     else
        currentWord = null;
  }

  public bool hasNextInt()
  {
     if (currentWord == null)
        return false;
     int dummy;
     return int.TryParse(currentWord, out dummy);
  }

  public int nextInt()
  {
     try
     {
        return int.Parse(currentWord);
     }
     finally
     {
        readNextWord();
     }
  }

  public bool hasNextDouble()
  {
     if (currentWord == null)
        return false;
     double dummy;
     return double.TryParse(currentWord, out dummy);
  }

  public double nextDouble()
  {
     try
     {
        return double.Parse(currentWord);
     }
     finally
     {
        readNextWord();
     }
  }

  public bool hasNext()
  {
     return currentWord != null;
  }
}
dustytrash
  • 1,519
  • 1
  • 8
  • 14
0

For taking non-numerical input, you can use Console.ReadLine(). For taking numerical or non-string input you should use Console.Read().

e.g

string s = Console.ReadLine();

int i = Console.Read(); //same goes for char, double, etc.

avigloz
  • 36
  • 7