我的背景是 Java,我正在学习一些 C# 编程语言代码。
我的问题是:Java 有一个 Scanner 类,用于从用户那里获取整数输入,在 C# 中是否有类似的东西
示例:Java
import java.util.Scanner;
class myClass{
myClass{
}
public static void main(){
//Scanner object
Scanner input = new Scanner(System.in)
input.nextInt();
}
}
C# 中的任何类似内容
是的,有Console.ReadLine
。
或者,您可以在 C# Stolen 中创建自己的 Scanner 类,从是否有与 C# 中的 Scanner 类等效的字符串?
class Scanner : System.IO.StringReader
{
string currentWord;
public Scanner(string source) : base(source)
{
readNextWord();
}
private void readNextWord()
{
System.Text.StringBuilder sb = new StringBuilder();
char nextChar;
int next;
do
{
next = this.Read();
if (next < 0)
break;
nextChar = (char)next;
if (char.IsWhiteSpace(nextChar))
break;
sb.Append(nextChar);
} while (true);
while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
this.Read();
if (sb.Length > 0)
currentWord = sb.ToString();
else
currentWord = null;
}
public bool hasNextInt()
{
if (currentWord == null)
return false;
int dummy;
return int.TryParse(currentWord, out dummy);
}
public int nextInt()
{
try
{
return int.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNextDouble()
{
if (currentWord == null)
return false;
double dummy;
return double.TryParse(currentWord, out dummy);
}
public double nextDouble()
{
try
{
return double.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNext()
{
return currentWord != null;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句