简体   繁体   English

如何用同一条输入线制作多台扫描仪?

[英]How to make multiple Scanners with the same input line?

I'm making a terminal game that uses Scanner objects. 我正在制作一个使用Scanner对象的终端游戏。 Up to now, I've had no problems with the way I did things. 到目前为止,我做事的方式还没有问题。 But now, I want to add "cheat-codes", for that I need a second Scanner . 但是现在,我想添加“作弊代码”,为此,我需要第二个Scanner One would be for the specified keywords that the players needs to type in to progress, the other would be for the cheat-codes, and I would make them in two separate Thread s, so they don't interfere. 一个将用于玩家需要输入以前进的指定关键字,另一个将用于作弊代码,我将它们设置在两个单独的Thread ,以免干扰。

The problem is, when I do this, the player is expected to type in two lines, since there's two Scanner s, but I want it to only ask for one line, and if that line is a cheat-code, it would do something different, from if it were a specified keyword. 问题是,当我执行此操作时,由于有两个Scanner ,所以播放器应键入两行,但我希望它只要求一行,并且如果该行是作弊码,它将执行某些操作与指定关键字不同。 Is there any way to do this, without needing to rewrite my code entirely? 有什么方法可以做到,而无需完全重写我的代码?

This is how I make the Scanner objects: 这是我制作Scanner对象的方法:

// show available keywords
System.out.println("[keyword1] [keyword2] [keyword3]\n");
Scanner User = new Scanner(System.in);
String user = User.nextLine();

if (user.contentEquals("keyword1")) {
    // code
}

(and I did the same for the other Thread with the cheat-codes) (我用作弊代码对其他Thread也做了同样的操作)

I have also tried it with a public static Scanner that I used for both Thread s, then just made a String for the keywords and another for the cheat-codes, but that, for some absurd reason, caused java.lang.IndexOutOfBoundsException to be thrown. 我还使用了我用于两个Threadpublic static Scanner进行了尝试,然后只是为关键字创建了一个String并为作弊代码创建了一个String ,但是由于某种荒唐的原因,导致java.lang.IndexOutOfBoundsException被抛出。

Thanks in advance! 提前致谢!

One scanner is enough. 一台扫描仪就足够了。

    String input1 = User.next();
    String input2 = User.next();

enter this values separated by space example you entered Hello World . 输入此值并用空格分隔,例如,您输入了Hello World the Hello goes to input1 then the World goes to input2 Hello进入input1然后World进入input2

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

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