gpt4 book ai didi

java - 将字符串传递到输入流

转载 作者:行者123 更新时间:2023-11-30 02:19:55 25 4
gpt4 key购买 nike

有人写了一个我想测试的类。它看起来像:

public class foo <E>{  
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
do_stuff(scan.nextInt());
}
}

我有另一个类尝试测试上述函数的 main 方法,如下所示:

public class Test{
public static void main(String[] args){
System.in.read("5".getBytes());
foo.<Integer>main(new String[]{});
}
}

基本上,我尝试使用 Test 类将输入提供到流中,该流很快将被 foo 中的扫描器读取。我根本无法更改 foo,因为它是别人的代码。

为什么这不起作用?正确的做法是什么?

最佳答案

您的System.in.read("5".getBytes())所做的是将一个字节数组传递给read方法,该方法尝试用用户输入。它完全忽略您放入该字节数组中的数据。

您必须调用System.setIn()来更改连接到System.in的流:

System.setIn(new ByteArrayInputStream("5".getBytes()));
foo.<Integer>main(new String[]{});

关于java - 将字符串传递到输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com