'How to make multiple Scanners with the same input line?
I'm making a terminal game that uses Scanner
objects. 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
. 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.
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.
Is there any way to do this, without needing to rewrite my code entirely?
This is how I make the Scanner
objects:
// 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)
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.
Solution 1:[1]
One scanner is enough.
String input1 = User.next();
String input2 = User.next();
enter this values separated by space example you entered Hello World
.
the Hello
goes to input1
then the World
goes to input2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NJY404 |