How to use the Scanner class to read two inputs separated by a Java space, and by two different variables?

Asked

Viewed 94 times

0

I am trying to do something simple, I would like that, given two arguments separated by a space, read through stdin, each be stored in a different variable, for example:

 Scanner s1 = new Scanner(System.in)

 Scanner s2 = new Scanner(System.in)

 input1 = s1.nextLine();

 input2 = s2.nextLine();

 a = input1 

 b = input2 

And the user writes in System.in, for example:

> Up Down

In the code I gave as example input1 and input2 are always reading the same things, I need one to read only the first argument and the other only the second argument.

Considering the example, how do I make the variable a receive only the string Up, and the variable b receive only the string Down?

  • 2

    You don’t need to create two scanners if they read from the same place (in this case, from System.in). Just use one that’s enough

1 answer

2


Just use one scanner and apply split(" ") to the String returned by him:

input = s1.nextLine();
String [] palavras = input.split(" ");
for (String palavra : palavras) {
    System.out.println(palavra);
}

String comando = palavras[0];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.