C# equivalent to Java's scn.nextInt( )

前端 未结 3 638
甜味超标
甜味超标 2021-02-11 08:12

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         


        
相关标签:
3条回答
  • 2021-02-11 08:52

    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.

    0 讨论(0)
  • 2021-02-11 09:00

    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()).

    0 讨论(0)
  • 2021-02-11 09:14

    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.

    0 讨论(0)
提交回复
热议问题