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

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

提交回复
热议问题