java - 如何正确编写 C# 帮助程序类以从单行读取多个整数?

标签 java c#

我正在尝试从 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/

相关文章:

java - 如何在 Kitkat Android 中将图像从一个 Activity 发送到另一个 Activity ?

java - Lambda 和流(数组)

c# - 为什么我的 ListView 不能正确显示详细信息 View ?

c# - 为什么我必须在 ASP 5 中的 app.UseMvc 之前调用 app.UseErrorHandler 才能正常工作?

java - Hazelcast - 关闭最后一个节点时保留数据

java - 如何创建第一列始终位于 JScrollPane 视口(viewport)中的 JTable?

java - Java中将所有字符大写并在每个字符之间添加空格的递归方法

c# - 从 Entity Framework 中的数据库更新模型不起作用

c# - 凯撒密码如何同时替换多个字母?

c# - 如何让 UI 线程等待信号量,但处理其他调度程序请求? (就像 MessageBox.Show 本身所做的那样)