0

我有一个类,用户在终端窗口上进行交互并输入某些选项,根据这些选项进行切换并使用某些方法;我需要使用扫描仪来检测用户输入。

我尝试了几天来创建一个测试类来模拟用户输入,但我找不到合适的方法,因为我无法为扫描仪模拟 System.in,也没有找到任何具体信息,我看到了一些关于缓冲,但我不能使用它。

这是一个尝试,它导致扫描仪出现 nullPointerException - 因为没有检测到输入。我还尝试休眠然后设置输入。

非常感谢为 Scanner 模拟 System.in 的示例。

public void test1addItem()
{
    InputStream input = new ByteArrayInputStream("".getBytes());
    String data1="1"; //Add an item option
    String data2="bread"; //The item to add

    input = new ByteArrayInputStream(data1.getBytes());
    //System.out.println("DATA1="+input);
    System.out.println("TEMP - 1");
    System.setIn(input);
    System.out.println("TEMP - 2");
    tsl.start(); //reference to the class which I am testing
    System.out.println("TEMP - 3");
    try {
        Thread.sleep(2000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    System.out.println("TEMP - 4");
    input = new ByteArrayInputStream(data2.getBytes());
    System.out.println("TEMP - 5");
    System.setIn(input);
    System.out.println("TEMP - 6");
}

它在 TEMP - 2 处停止,因为它是一种递归方法,直到给出某个选项来终止程序。

4

2 回答 2

0

这个想法背后的基本推理是有缺陷的。我假设你想做类似的事情

scanner.read(2);

但是,Scanner 被设计为从标准输入和文件等 InputStream 中读取。它需要一个源来读取,而像 2 这样的常量只是一个无效的源。

如果您在调用 readLine() 时使用将 2 作为输入的方法,也会出现问题。扫描仪仅在您调用 read 方法时才开始阅读,并且在完成阅读之前它们不会停止。所以如果你要做

String s = scanner.readLine();
scanner.feed("hi");

代码永远不会到达第二行。如果你要做

scanner.feed("hi");
String s = scanner.readLine();

扫描仪永远不会看到“嗨”,因为它是在扫描仪读取之前输入的。

您也许可以设置某种只输出恒定“hi”的流,但仅从 System.in 或文件自己模拟输入更为实用。

您也可以将变量设置为输入的内容!例如:

String s = "hi";   //scanner.readLine();
于 2015-10-20T20:33:42.667 回答
0

您是否尝试过重新分配 System.in?

System.setIn(new ByteArrayInputStream("data".getBytes()));
于 2015-10-20T20:31:02.667 回答