11 September 2020

How to get user input in Java?


Welcome back to another tutorial on the "How to code in Java" tutorial series. In the last tutorial, I explained what conditional statements are and how are they used. If you haven't read it, feel free to read it since you might learn something new by reading it. In this tutorial, we'll be going through how to get the user's input from the terminal in Java. I'll be showing you how to quickly get the user's input from the terminal using a class's object along with its method to get different types of input. If you don't know what method, class or object is, please read my other tutorial for a quick explanation.


Index for the tutorial:



The Scanner class


This would be the easiest way to take input from the user's terminal. The Scanner class is used to parse input that user provides in the terminal into tokens (symbols that our Java compiler understands) and could be converted into different types by using various next() methods. The types are parsed with the help of regular expressions. A regular expression is a sequence of characters used for searching values with a specific pattern. By defaults, the Scanner used whitespace " " as the delimiter to separate the input's value into tokens. You could change the delimiter to match another pattern too if you want to but we won't be covering that here. Another thing is that there are actually many other different ways that you could use to take input from users, so don't think Scanner is the only way. Now let's get started with how to use the Scanner class.



Importing the Scanner class and Initialising its object.


To get started to open up a new java file and initialise the main method, main inside the file class. Then, import the Scanner from Java.util package. The java.util package is just a collection of useful frameworks and many other utilisation classes. Then inside the main method, initialise a Scanner object while providing the standard input stream (System.in) as the constructor of the object. System.in is the standard input stream in Java which are used to read input from the user's keyboard or other specified input device specified by the machine's environment.


Importing and initialising the Scanner's class and its object.



Scanner's next() method.


Now, to simply get user input from the terminal, simply use the next() method inside the Scanner object. The next() method would read the next token as a string (no matter the value is a character or a numbers data type).


Using the Scanner's next() method.

The result for the code above.


As you can see, it works like a charm. When you entered a value into the terminal and pressed enter, the Scanner object would scan the whole inputs from the terminal. Then, the next() method would read the next token (a word before a space character). But what do you think will happen if we add another word as the input where the two of them are separated with space? The Scanner will first scan the whole string input, then converts them into tokens. But when we call the next() method, only the first word provided by the user will be taken. In a more precise way to describe it is, the method stops after it founds its first token, ignoring the tokens (inputs) after that.


Only one token will be taken when using next()



Taking the next token after used the first next() method.


To get the next input value, that's ignored in the first next() method. We just need to use the next() method again, to get the next token of the input. This also applies to the other next method in the Scanner class. 


How to get two input's using two Scanner's next() method.


Output for the code above.



The nextLine() method.


Next, we can also specify the Scanner to get the entire string from the user using the nextLine(). This method will receive inputs from the user until the Scanner found a newline character token ("\n"). This character is automatically inserted into our inputs whenever we press enter after we have finished writing inputs in the terminal. But that doesn't mean that you can stop the input scanning halfway by providing the Scanner with a "\n" string in the input's value. That's because the nextLine() method will escape the escape sequence automatically.


Using Scanner's nextLine() method.


The output for the code above.



The escape sequence is escaped automatically.



How to get numbers token from the Scanner's object.


Now, let's look at what do we need to do to make the Scanner to take in integer value instead of strings value. Since Scanner scans the next input and parses it into tokens of different type of primitive types, we can get different primitive types of data from the user easily. Here's a list of the method to get numbers from the user.

Getting integral values from the Scanner.



Getting floating number token from the Scanner.  

Getting integer value from the next token in Scanner.

Demo for the code above.


When scanning for integral values (whole numbers), you can also provide the method with an argument which specifies what radix to be used to interpret the token (hexadecimal, binary, decimal and many more). For example, to take a hexadecimal input and change it into a decimal, we can use any of the Scanner's method used for scanning integral numbers (nextInt, nextShort, nextByte, nextLong and nextBigInteger[not covered in this tutorial]). But one thing to get noticed is that you'll need to also take into account their memory size limitation. For example, a Short data type could only store number as big as 32767 and as small as -32768 in decimal (total size of 2 ^ 16). For more information regarding data types size limitation, please read this tutorial on variables in Java. If you somehow entered a value that's bigger then its limits, then you get a runtime error.


Using nextInt() with a radix provided. (the other integral method also can do the same thing)


Output for above code.


Runtime error caused by the inappropriate use of types of next() method.


To specify a negative binary number, you can simply add a negative sign (-) in front of the number.


Negative numbers in hexadecimal.



The nextBoolean() method.


Besides taking strings and numbers value from the user, the Scanner could also take a boolean value from the user.


Getting a boolean value from the next token in the Scanner object.

Output for the code above.


One thing to remember is to close your Scanner after finishing using it. This is used to freeing up unused resources and avoid the system to waste resources needlessly (it happens when you've a huge program).


Closing the Scanner object.



Now the final thing that you'll need to know is that if let's say the next token is a String type input. But you used the nextInt() method because you thought it to be an int type. What happens is that this will cause our program to crash because a runtime error has occurred (an error that occurs during interaction with the program).


Well, that all that you'll need to know to get the input from the user's terminal. I hope you now know how to get inputs from the user and how Scanner works (in the surface of course). If you find this tutorial helpful, please share it with other peoples that might be interested in it. Also as usual, if you have any questions, critics or suggestions for the tutorial or my blog, feel free to leave a comment below or contact me through any of the provided contacts methods. You can contact me using my contact information in the about page. Thank you for reading this tutorial, in the next tutorial we'll be going through on how loops work in Java. So stay tuned.

No comments:

Post a Comment