How do I use Scanner to capture keyboard inputs?

Asked

Viewed 460 times

6

I would like to know how to use the Scanner in the java to simulate cin and cout of c++

1 answer

9


Using the Scanner you can capture data entry using the methods below, which are the most common:

Scanner s = new Scanner(System.in);

s.nextInt();
s.nextDouble(); 
s.nextFloat(); 
s.next(); //captura como string mas se o trecho tiver espaço, ignora o que
          //estiver após o espaço. Não move o scanner pra linha seguinte
s.nextLine();// captura como string uma linha inteira e para após uma quebra
             //de linha, move o scanner para a linha seguinte

You just need to be careful when using primitive type captures with String captures, because of the leakage of the line breaking.

And for data output, java has the System.out.println() which displays information by inserting a line break, and the System.out.print() that does the same thing, only without the line break.

  • what method not to pick up memory junk ?

  • @Rodolfo The problem occurs when making a capture using nextLine() right after capturing a primitive type, but you can catch the linebreak giving a s.nextLine() before making the next String capture. @Math makes another cool suggestion here,

Browser other questions tagged

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