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

前端 未结 3 634
甜味超标
甜味超标 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 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.

提交回复
热议问题