我正在尝试从 Java 切换到 C#,并且也在练习竞争性编程问题,但我发现 C# 没有像 Scanner.nextInt( )
。公平地说,我在 Java 中也不使用这种方法,而是使用一个辅助类来执行如下操作:
(这是一个静态内部类):
static class InputReader {
public String[] input;
public BufferedReader reader;
ublic int current;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
input = null;
current = 0;
}
public String next() {
while (input == null || current == input.length) {
try {
current = 0;
input = reader.readLine().split("\\s");
} catch (IOException e) {
throw new RuntimeException();
}
}
return input[current++];
}
public int nextInt() {
return Integer.parseInt(next());
}
}
我尝试用 C# 重写相同的内容,结果如下:
internal static class InputHelper
{
private static int current;
private static string[] buffer;
public static string next()
{
while (buffer == null || current == buffer.Length)
{
current = 0;
buffer = Console.ReadLine()?.Split();
}
return buffer[current++];
}
public static int NextInt()
{
return int.Parse(next());
}
}
但是,当我从问题陈述中粘贴此序列时,出现异常 (NumberFormatException):
3
5 1
3
3 3
1 2 3
4 1
1
编辑:我怀疑它会抛出异常,因为 Windows Linux 上使用了不同的换行符,但这可能是完全错误的。
其他时候例如:
var n = InputHelper.NextInt();
while (n > 0)
{
n--;
Console.WriteLine(InputHelper.NextInt());
}
它工作得很好。关于为什么它可能是错误的任何想法?
最佳答案
我不知道为什么你的不起作用,但你可以尝试这个:
public static class ConsoleHelper
{
private static string[] input = new string[0];
private static int inputIndex;
public static void ReadNextInput()
{
input = Console.ReadLine().Split();
inputIndex = 0;
}
public static int GetNextInt()
{
return int.Parse(ReadNextWord());
}
public static string GetNextWord()
{
return ReadNextWord();
}
private static string ReadNextWord()
{
if (inputIndex >= input.Length)
{
ReadNextInput();
}
return input[inputIndex++];
}
}
我一直在比赛中使用它,到目前为止,从未让我失望过。
编辑:
您可以尝试以下拆分:Split(' ', StringSplitOptions.RemoveEmptyEntries);
这会自动删除输出数组中的空元素。
关于java - 如何正确编写 C# 帮助程序类以从单行读取多个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48664794/