相当于Java的cn.nextInt()的C# [英] C# equivalent to Java's scn.nextInt( )

查看:140
本文介绍了相当于Java的cn.nextInt()的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如果我们想从控制台读取用户输入,则可以执行以下操作.

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 integer input

在C#中,我假设我们这样做:

In C#, I am assuming we do this:

int x;

x = Console.Read();  //Receive integer input

但是当我输入7时,输出为55.

But when I enter 7 , the output is 55.

另外两个用于读取输入的选项是ReadLine()(可能用于读取字符串)和ReadKey()(可能用于检测您按下的键)(如果我输入错,请更正我 ).

The other 2 options for reading inputs are ReadLine() which is probably used for reading strings, and ReadKey() which is proabably for detecting which key you pressed (Please correct me if I am wrong).

请不要告诉我,我们每次都必须使用ReadLine并将整个值解析为int,这很糟糕:-(

Please don't tell me that we have to use ReadLine and parse the entire value to int everytime, that will be awful :-(

编辑:在SO中,提出了类似的问题(

In SO, a similar question was raised (c# Console.Read() and Console.ReadLine() problems), but all the solutions given was to use int.TryParse and series of codes just to receive a int or double input, which I find it too inconvenient just to do a simple task.

我发现我们实际上可以做到:

I found out that we could actually do this:

int a = int.Parse(Console.ReadLine());

因此,除了问一个重复的问题, 我的新问题是:当我使用int a = int.Parse(Console.ReadLine());接收int输入时,它是否等同于Java的scn.nextInt()?

So instead of asking a duplicated question, my new question is: Is it equivalent to Java's scn.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

推荐答案

当我使用int a = int.Parse(Console.ReadLine());时,它是否等效于Java的scan.nextInt()?接收int输入?

Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

是的. Java的 Scanner.nextInt() 没有收到整数输入时会引发异常,.NET的int.Parse(Console.ReadLine())也是如此.

Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine()).

这篇关于相当于Java的cn.nextInt()的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆