In Java, if we want to read an user input from the console, we can do the following.
Scanner scn = new Scanner (System.in);
int x;
x = scn.nextInt(); //Receive
Yes, you need to use ReadLine, parsing the input is not so hard.Just use TryParse method:
int input;
bool isValid = int.TryParse(Console.ReadLine(),out input);
if(isValid)
{
...
}
Console.Read
reads the next character from console, and it returns the ASCII
code of the char, that's why you are getting 55
instead of 7
.
Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?
Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine())
.
This may be a year late, but...
static int GetInt() {
int integer = 0;
int n = Console.Read();
while (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
n = Console.Read();
while (n >= '0' && n <= '9') {
integer = integer * 10 + n - '0';
n = Console.Read();
}
return integer;
}
This is more or less the same as Java's nextInt() method. It doesn't support negative values as it currently is, but it can be easily implemented by checking if the first read value is '-' and if it is, multiply the final value by -1.