简体   繁体   English

来自InputStream的扫描仪输入

[英]Scanner input from InputStream

I'm doing test driven development which requires me to write a test function for a class that takes input from the user. 我正在进行测试驱动的开发,这需要我为需要用户输入的类编写测试函数。 Since the console input function stops for input during tests, I wrote the tests using an InputStream which uses a string. 由于控制台输入功能在测试期间停止输入,因此我使用了使用字符串的InputStream编写了测试。

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

This leads to the calling of the function getChoice(InputStream i) which involves console input from a Scanner. 这导致调用函数getChoice(InputStream i),该函数涉及来自扫描仪的控制台输入。

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;
    }

I want the above code to take the numbers in the string one by one. 我希望上面的代码一个接一个地取字符串中的数字。 But, what is happening is that it takes the first number properly and then, the position of the stream goes directly to the end of the stream which causes a NoSuchElementException. 但是,发生的事情是,它正确地获取了第一个数字,然后,流的位置直接转到流的末尾,从而导致NoSuchElementException。 Please Help! 请帮忙!

采用...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM