Buzz Code
Published in

Buzz Code

Java 8 | Scanner Class

Scanner Class — One of the java.util.package that gets user input.

Hi guys! So until the last time we’ve been practicing the two dimensional array. Today we’re gonna learn something new that you might find interesting!

[Scanner]

So with the Scanner class you can type something in from the console.

First you need to create the new Scanner class and then put it in the Scanner variable.

Here, you see we’re passing the System.in as a parameter, it is an standard inputStream, and that is typically keyboard. And then if you hit the ctrl+shift+O to import, we’re ready to go.

So I used println() method to let people know what to do. And then I declared the String input and put the in.nextLine() in the input . Then I used println() method again to print what’s stored in the String input .

Here, because of the nextLine() method, the code behind it doesn’t show up on the console yet, until you actually type something in on the console. The nextLine() method doesn’t accept any parameter, and returns String type data which the user typed in. Also it returns the value when you hit the enter key.

Just like this! And there is also a nextInt() method which can get the integer numbers from the keyboard.

You see I put the in.nextLine(); after the nextInt() method. This is called clearing buffer . We need to clear the buffer because we have to type enter even when we type integer numbers. And the program consider that line changing is another String data that it’s getting, so it can occur some problem. For instance, let’s say we have to get the numbers and the text from the users.

If I didn’t clear the buffer, input2 will be automatically getting the line changer as its value. And this is not we want.

But if I cleared the buffer,

It will work very well like this.

Okay, that’s all for today, and let’s do something fun with using Scanner class next time. Thank you for reading my post, see ya!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store