ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 5

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 4 | Lesson 6 >>

_______________________________________

Lesson 5: Working with user inputs in Java

Source

Welcome to lesson 5 of Programming in Java. In Lesson 4 we learnt how to work with variables in Java and how to manipulate computer memory using variables. We also saw the use of different data types (int, double, float, String and char) in Java.

For this lesson, you will need to create a new class in myfirstprogram package. So, right click the package myfirstprogram, select New option from the menu and then select Java Class.


Source

Let us call the new class UserInputs so, from the New Java Class window that will appear, enter UserInputs as the Class Name. Click Finish.

Source

Now, delete all the comments in the code editor window as we did earlier and then include the “main” method in your class. Your code editor window should look like shown below:

Source

As I mentioned earlier, Java contains a lot of functions or methods that are really useful to a programmer. These methods are written to accomplish a specific task that you may need to execute in your applications.

Related methods are grouped together and stored as a class. Related classes are stored in a package in Java library. When we want to use a certain method in Java, we reference its package and then the class into which it belongs.

One of the useful classes that handle inputs from a user in Java is the Scanner class. The Scanner class is located in the util (utility) package of the Java library. To use the Scanner class, we use the keyword import to reference it in our code, see below.

import java.util.Scanner;

The above statement tells Java that you want to use the Scanner class located in the util package of the java library. To use the class, we create new object of the class. This object work as the link between our code and the class and so we can be able to access the functions of the class from our code. We create the new object by using the following code:

Scanner user_input = new Scanner( System.in );

Notice that instead of creating an int variable or a String variable, we are creating a Scanner variable. We have called our Scanner variable user_input. After an equals sign, we have the keyword new. The keyword new is used to create new objects from a class. Here, we are creating an object from the Scanner class. In between the brackets we are specifying that the object is for a system input and we show this by including System.in inside the brackets.

To get the inputs from the user, we are going to use our new object, user_input, to call one of the many input methods available in the Scanner class. We’ll use the next method. This method gets the next string of text that a user types on the keyboard. It is one of the many methods in Scanner class. As you type next in the code editor you’ll see a list of other available methods.

Scanner user_input = new Scanner( System.in );

String user_name; user_name = user_input.next( );

Before we take the user name as input, we’ll add another statement to ask the user to enter the input. We have also created a String variable called user_name to store that input.

Scanner user_input = new Scanner( System.in );

String user_name;

System.out.print("Enter your name: ");

user_name = user_input.next( );

Notice that we have used print instead of println like we did earlier. The difference between the two is that println makes the cursor to move to a new line after the output, but with print the cursor stays on the same line. Let us now add our popular method to output the user input on the output window.

Scanner user_input = new Scanner( System.in );

String user_name;

System.out.print("Enter your name: ");

user_name = user_input.next( );

System.out.println("Your name is: " + user_name);

You code editor window should now look like shown below:

Source

To run your program, go to the project window, right click your program and select Run File

Source

When you run the program, Java will pause and ask you to enter your name, enter a name of your choice and press enter. You should be able to see the output as shown below:

Source

Exercise: Modify your code so that you can input sir name and family name.

In the next lesson, we shall look on how to use Java Option panes for input and outputs purposes.


<< Lesson 4 | Lesson 6 >>

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)