gpt4 book ai didi

java - 在 hasNext() 返回 false 后更改扫描仪的输入

转载 作者:行者123 更新时间:2023-12-01 23:44:44 25 4
gpt4 key购买 nike

我正在使用扫描仪的自定义输入流并想要更改它。但在第一次读取和更改 InputStream 中的数据后,它会停止。

我可以修改我的代码以进行二读吗?走哪条路?

更新我将此代码与其他程序一起使用,并将它们的标准输入重定向到我的。所以我需要更改 System.in 并且无法重新创建 Scanner。

这是我的类(class):

class CRStream extends InputStream {
private ByteArrayInputStream in;
public synchronized int read() throws IOException {
int x = in.read();
return x;
}
public synchronized int read(byte[] bytes, int off, int len) throws IOException {
return in.read(bytes, off, 1);
}
public void set(String utf8str) throws IOException{
try{
in = new ByteArrayInputStream(utf8str.getBytes(StandardCharsets.UTF_8.name()));
}
catch (UnsupportedEncodingException e){}
}
}

以及使用示例

public class Main {
public static void main(String[] args) throws IOException {
CRStream in = new CRStream();
System.setIn(in);
Scanner scanner = new Scanner(System.in);
//Everything is OK
in.set("Word1 Ok Word2 Ok");
while (scanner.hasNext()){
System.out.println(scanner.next());
}
//Does not work... Prints nothing
in.set("WORD3 Ok WORD4 Ok");
while (scanner.hasNext()){
System.out.println(scanner.next());
}
}
}

这是第二个例子

一个简单的客户端程序

class ClientProgram {
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(in.next());
}
}

我用代码测试了

public class Main {
public static void main(String[] args) {
CRStream in = new CRStream();
System.setIn(in);
in.set("Test1");
ClientProgram.main(new String[0]);
in.set("Test2");
ClientProgram.main(new String[0]);

}
}

在第二次测试中,它出现了 NoSuchElementException

最佳答案

只是好奇,当扫描仪可以直接读取字符串时,为什么要跳过这么多麻烦:

public static void main(String[] args) throws IOException {

Scanner scanner = new Scanner("Word1 Ok Word2 Ok");
while (scanner.hasNext()){
System.out.println(scanner.next());
}

scanner = new Scanner("WORD3 Ok WORD4 Ok");
while (scanner.hasNext()){
System.out.println(scanner.next());
}

如果您希望 Ok 作为分隔符,您可以在扫描仪上调用 useDelimiter("Ok ")

至于实际问题,我怀疑内部扫描仪可能正在缓冲您的输入流,并且没有意识到您已经在其上拉了一个 switcheroo;也许无论如何都要制作一个新的扫描仪或重置()你的crinputstream。也无需用您的系统输入流替换系统输入流,然后将扫描仪连接到系统输入;扫描仪可以从您的输入流中读取数据,而无需通过 system.in

关于java - 在 hasNext() 返回 false 后更改扫描仪的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245377/

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