【问题标题】:Scanner input from InputStream来自 InputStream 的扫描仪输入
【发布时间】:2012-07-25 04:36:57
【问题描述】:

我正在进行测试驱动开发,这需要我为一个接受用户输入的类编写一个测试函数。由于控制台输入功能在测试期间停止输入,因此我使用使用字符串的 InputStream 编写测试。

String str="3\n2\n1\n4\n";
InputStream is = new ByteArrayInputStream(str.getBytes());
assertTrue(app.RunApp(is));

这导致调用 getChoice(InputStream i) 函数,该函数涉及来自 Scanner 的控制台输入。

public int getChoice(InputStream i) throws IOException {
        Scanner s=new Scanner(i);
        s.useDelimiter("\n");
        String y= s.next();
        int x=Integer.parseInt(y);
        return x;
    }

我希望上面的代码一个一个地取字符串中的数字。但是,发生的事情是它正确地采用了第一个数字,然后流的位置直接进入流的末尾,这导致了 NoSuchElementException。请帮忙!

【问题讨论】:

    标签: java console


    【解决方案1】:

    使用...

    String y = s.nextLine();  // That will take the entire line instead of only 1st word
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      相关资源
      最近更新 更多