In our examples, we had to provide all data directly in the program’s code. It is neither convenient nor useful, because even the simplest calculator must have the function of getting the data from the user. The entry and exit streams that we will mention in this post are used for this purpose.

Displaying Data

We have already seen our data on the screen many times. We used the System.out.print(data) for this purpose. Unfortunately, this method does not give us too much room to show off :), we have no control over the displayed data.

Obtaining data from the user

You can use several mechanisms for this purpose, for example, Buffered Data Reading, but we will start with something a bit simpler. The System.in stream is used to retrieve information. The Scanner class is connected to it, thanks to which we will write a simple program that receives its name and displays a greeting from the user.

First of all, we import the appropriate class, ie Scanner.

First, we declare a variable name in which we get the data from the user. Next, we create a new Scanner object. We have two stages here, declaration

and then we create the object using the new operator

We saved both of the above instructions on one line. As you can see, creating an object is similar to declarations and initialization of simple types. Object-oriented programming, , will be dealt with it later.

As a constructor parameter of the Scanner object, we gave the System.in input stream, thanks to which we will now be able to communicate with the user.

At this moment, the user receives data from user, i.e. user enters the ‘Enter Key’.

The Scanner class also offers a number of other methods to read other types of data:

  • nextInt () – reads the next integer
  • nextDouble () – reads the next floating point number (note, the separator can be either a dot or a comma – it all depends on the country standard on which the virtual machine is set – this can be set using the useLocale (Locale) method)
  • etc. there are also a number of useful functions that can be useful for example when reading files, you can read them in the Scanner Class API.

LEAVE A REPLY

Please enter your comment!
Please enter your name here