在Java中,如果我们想从控制台读取用户输入,我们可以执行以下操作。
Scanner scn = new Scanner (System.in);
int x;
x = scn.nextInt(); //Receive integer input
在 C# 中,我假设我们这样做:
int x;
x = Console.Read(); //Receive integer input
但是当我进入7
,输出是55
.
读取输入的其他 2 个选项是ReadLine()
这可能用于读取字符串,并且ReadKey()
这可能是为了检测您按下的键(如果我错了请纠正我).
请不要告诉我我们每次都必须使用 ReadLine 并将整个值解析为 int,那会很糟糕:-(
EDIT:在SO中,提出了类似的问题(c# Console.Read() 和 Console.ReadLine() 问题 https://stackoverflow.com/questions/12308098/c-sharp-console-read-and-console-readline-problems),但给出的所有解决方案都是使用int.TryParse
和一系列代码只是为了接收int
or double
输入,我觉得仅仅做一个简单的任务太不方便了。
我发现我们实际上可以这样做:
int a = int.Parse(Console.ReadLine());
因此,不要问重复的问题,我的新问题是: 和Java的一样吗scn.nextInt()
当我使用int a = int.Parse(Console.ReadLine());
受到int
inputs?
当我使用 int a = int.Parse(Console.ReadLine()); 时,它是否相当于Java的scanner.nextInt();接收 int 输入?
是的。爪哇的Scanner.nextInt() http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29当没有收到整数输入时抛出异常,.NET 也是如此int.Parse(Console.ReadLine())
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)