Wednesday, March 7, 2018

User Input using Scanner class in java


User Input is one of the basic fundamental requirement of the application , In the series of Tutorials we’ve been doing this for a while now, and I want to believe that anyone reading this is learning as much as he or she can, and putting that knowledge to some form of practice. I’ll do as much as I can to teach you what I know, and what I can gather, but it will be pointless doing this if nobody is learning anything. Always remember, practice makes perfect. And a little practice can teach you a lot more than any tutorial video can.


Before move further let see all the previous posts



Last week, we talked about data structures and different data types, and we talked about variables, and we did a lot of other cool things. But we’ve been dealing a lot with fixed variables, and you’re probably thinking “what if I want to enter any two numbers, like a normal application” or “how do I make it look like a normal app?”, and it’s true; it won’t be practical for someone who’s not a coder. You might want the user to enter his values, instead of inserting it into the code.
Well, obviously Java has these things available; otherwise most apps and games are a product of witchcraft. In fact, due to Java’s vast library of codes, there are different classes you can call to enable user input.


The Scanner Class


This is a very basic class that allows you to enter input into the console and store it into a set variable. It’s pretty similar to the ‘scanf’ function in C or the ‘cin’ function in C++ (if you’re completely new to code and don’t get these references, basically, it allows you to enter input). You can do the basic calculations with this class, and it makes it more interactive for those not familiar with code.



Now make a new project or file and call it “ScannerPractice”, and delete the comments (if you want to). Before you can use the Scanner class, you have to call it into the class file from the ‘java.util’ library using the ‘import’ keyword, just like so:

Import java.util.Scanner;


You’ll have to do this over the class statement, so that it’ll look like this:




Never mind the yellow line under it, it’s just saying that the class hasn’t been used yet. If you hold your pointer under it, it will say ‘unused import’. If you run it, it should run without errors. If the line itself disturbs you, don’t worry, we’re going to use it.


Add this to your main method:



Now I’m going to explain everything here one by one, but basically what this is going to do is allow you to enter your first and last name, store them into two separate variables, and print them out on the console. This:




Scanner user_input=new Scanner(System.in);



…is the code to call the imported scanner class into our main method.

 You can see that we called it as a variable, but the data type there is known as a Scanner, not an int or String. It is given the name ‘user_input’, after which we put an equals sign and the keyword new. What that does is creating a new object from the Scanner class. In the bracket after ‘Scanner’, you see ‘System.in’; this is the opposite of ‘System.out’ and is basically java to enable input capabilities.



String firstName;
System.out.println("Enter your first name:");
firstName = user_input.next();


These are the next lines of code we write. What this does is take in our input and save it into a variable (in this case, the String variable named “firstName”). The console will first print the message “Enter your first name:”, after which it will prompt you to enter said information. The string of text will be collected using a method from the scanner class called ‘next’. This is called by typing ‘.next()’ after the Scanner variable name, which you’re saving into the String.


Long story short, this will let you input text and save it into a variable. After those lines you’ll need to put these:



String lastName;
System.out.println("Enter your family name:");       
lastName = user_input.next();



This does basically the same thing, with the differences being the name of the variable, the message to be printed out, and the information. If we want to print out the information that we’ve entered, we can use these lines of code:



String fullName = firstName + " " + lastName;
System.out.println("Hello " + fullName + "!");

Now we’re just putting the two variables together using concatenation and saving it into a String variable called fullName. The double quotes represent a space in the middle of the two strings. After that, you put a statement to print out your input with the word “Hello” and an exclamation mark.
If you run it, the output window should display this:

The code will display your first message, the pause to let you input your answer. Type in your first name and press the enter key:
The second message should pop up the second you click Enter. Type in your last name and press enter. Your final message will appear, and your output window should display this:
This is the use of the Scanner class in a nutshell. If you like, you can try it out with your initials. Try making a scanner class that accepts characters and prints out your initials. In fact, after that, you can make a simple calculator that allows you to input integers or floats and adds, subtracts, multiplies, divides or performs other forms of arithmetic operations; like Simple Interest or Arithmetic Mean.
Now let’s move on:

Scanners are cool and all, but…


Now you’ve learnt how to enter user input. Kind of cool, ain’t it? Well it may not be to some of you. Most people may not really like using the Scanner class, especially since the java console isn’t graphical. For example, when I started using the Scanner class, I was like “This is cool and all, but when do I get to the good stuff.
Well, if you are interested in something more graphical, another class you could consider is the JOptionPane.

Java Option Panes

The JOptionPane class allow you to generate input dialog boxes like this:
…or message boxes like this:

So how about we adapt what we did earlier and add some option panes. We’ll start the way we started the Scanner class, by importing the class into our java file. Go to where we wrote our Scanner input and change it to this:
import javax.swing.JOptionPane;
This imports the JOptionPane class from the javax.swing library, the same way we imported the Scanner class from the java.util class.
Now lets overhaul our code. (If you still want to keep the Scanner class file, you’re free to create a new project, or class filr). Change this:


String firstName;
System.out.println("Enter your first name:");
firstName = user_input.next();
…to this:
String firstName = JOptionPane.showInputDialog("Enter your first name:");
…this:

String lastName;
System.out.println("Enter your family name:");
lastName = user_input.next();
…to this:

String lastName = JOptionPane.showInputDialog("Enter your last name:");
…and this:

String fullName = firstName + " " + lastName;
System.out.println("Hello " + fullName + "!");
…to this:

String fullName = firstName + " " + lastName;
JOptionPane.showMessageDialog(null, "Hello " + fullName + "!");
Also, you should remove this line altogether:
Scanner user_input=new Scanner(System.in);
…and at this at the end of everything:
System.exit(0);
… and at the end of it all, your code should look like this:


So before we run it, let’s do a quick breakdown on what it does exactly. The first few lines of code takes your message, prints it out as an input box (showInputDialog) and allows you to input the required information; saving it into the String variables ‘firstName’ and ‘lastName’. It then combines the two variables and saves them in a new String (fullName). After which a showMessageDialog method is called, which prints out our message in brackets on a message box.
Note: The keyword null just means that the message box is not associated with anything else in the programme. Also, the last line (System.exit(0)) ensures that the program exits, clearing all created objects from the system’s memory.
Alright, now that we have an idea of what this does, run the program. After some time, our first input box will appear:

Type your first name and click ‘Ok’ or press Enter. The second dialog box will appear. Type your last name and click ‘Ok’ again:

If you did it all right, you’re message box should display a message like this:

Click ‘Ok’ to end the program. And congratulations, you’ve run your first JOptionPane.

Working with Numbers

Just like the Scanner class, you can also work with numbers in Option Panes. This would normally be the part where I tell you to try and find how it works, but numbers work differently here than in Scanners, and it would give me a chance to explain something important to you.
Delete or comment out the lines of code you’ve already written. We’re going to create a simple calculator to add two numbers together. Add this as your first line of code.




String firstNumber = JOptionPane.showInputDialog("Enter your first number:");

String secondNumber = JOptionPane.showInputDialog("Enter your second number:");

Now before we move forward, notice that the input is being saved into a String. We cannot add two Strings together, so we’ll have convert them into integers. We can do that using this:

Integer.parseInt(String to convert);
So what we do now is create an integer variable called answer, where we print out our answer, and save the sum of the two converted strings into it, after which we print it out into a message box; kind of like this:

int answer = Integer.parseInt(firstNumber) + Integer.parseInt(secondNumber);
JOptionPane.showMessageDialog(null, "The sum is " + answer);
 Run it and see what happens. Does it work? It most likely does.

Before we sign off…

There are different ways we can format your Option Panes. You should make a point of trying them out. We can add header names to our boxes, by adding this:

showInputDialog ("Your Name", "Enter Your First Name");

…and for your message box, you can choose what form of message box it can be. Try this:


showMessageDialog(null, fullName, "Your Name", JOptionPane.INFORMATION_MESSAGE);
…and after that, you can try with other options. Remember, practice makes perfect.
 You remember 10% of what you read, and 90% of do yourself.

If you like this article please share it with your friends and colleagues. Leave us a comment.

Happy Learning

Thanks for reading
Noeik 





0 comments:

Post a Comment