Wednesday , December 19 2018

JAVA #14 – Dynamic user input on Array in Java (Console)

Share on WhatsApp
Share via email Share

 

Dynamic user input on Array in Java

One of the strengths of Java is the huge libraries of code available to you. This is code that has been written to do specific jobs. All you need to do is to reference which library you want to use, and then call a method into action. One really useful class that handles input from a user is called the Scanner class. The Scanner class can be found in the java.util library. To use the Scanner class, you need to reference it in your code. This is done with the keyword import.
The import statement needs to go just above the Class statement:
 

This tells java that you want to use a particular class in a particular library – the Scanner class, which is located in the java.util library.

The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of code. It doesn’t do anything until you create a new object from it.)

To create a new Scanner object the code is this:

So instead of setting up an int variable or a String variable, we’re setting up a Scanner variable. We’ve called ours user_input. After an equals sign, we have the keyword new. This is used to create new objects from a class. The object we’re creating is from the Scanner class. In between round brackets we have to tell java that this will be System Input (System.in).

To get the user input, you can call into action one of the many methods available to your new Scanner object. One of these methods is called next. This gets the next string of text that a user types on the keyboard:

So after our user_input object we type a dot. You’ll then see a popup list of available methods. Double click next and then type a semicolon to end the line. We can also print some text to prompt the user:

Notice that we’ve used print rather than println like last time. The difference between the two is that println will move the cursor to a new line after the output, but print stays on the same line.

We’ll add a prompt for a family name, as well:

This is the same code, except that java will now store whatever the user types into our family_name variable instead of our first_name variable.

To print out the input, we can add the following:

We’ve set up another String variable, full_name. We’re storing whatever is in the two variablesfirst_name and family_name. In between the two, we’ve added a space. The final line prints it all out in the Output window.

Share on WhatsApp
Share via email Share

About Faheem

Check Also

JAVA #32 – Java application using SQL server (Part: 01)

  In this part we made the GUI front end of a Application. Related

Leave a Reply

Your email address will not be published.