Learn Java Easy. Chapter 3. Rich’s Friend / Keyboard Data Input

Chapter 3: Rich’s Friend / Keyboard Data Input

Chapter 3. Rich’s Friend / Keyboard Data Input

Two days have passed since the party and it’s time to clean up. It can’t be said that it’s one of my favorite activities, but this time there’s no other option. I can’t stop thinking about how lucky Chani is to get out of this unpleasant task. Much of the people who came to the party were his friends, and it doesn’t seem fair to clean up what they’ve messed up. Although, thinking better of it, we didn’t know the reason why he suddenly left. It’s very possible that it was for something important, and the fact that he’s not answering the phone worries me quite a bit.

On the other hand, I’m angry. Among other belongings, my laptop is trapped inside his closet. A question keeps going through my head: why, before leaving, did he take his time to tidy up his room? If you need to leave urgently, you simply grab what you need and go.

Rich seems calm, barely says anything. From time to time he smiles and seems to have his mind elsewhere. He hardly spoke to me all day. But I’m not surprised at all. He’s sometimes like that.

He starts thinking about his things and spends hours without talking to anyone. Although the truth is that, in that state, he’s quite productive. He has an amazing ability to concentrate. I think that’s why he’s a better student than me. At the moment, I prefer not to bother him and let him concentrate on cleaning. The sooner we finish, the better. I’ll leave him cleaning the kitchen while I scrub the rest of the house. After this, everything should be clean.

Finally, it seems he’s finished this torture. After several hours of suffering, I can say we’re done. My plan is to lie on the sofa for the rest of the day. Rich, on the other hand, seems to have made plans with someone. I imagine he’s going to leave the house soon. He’s in the bathroom getting ready, so he could be there for hours. He loves looking at himself in the mirror and always leaves the house perfectly groomed.

I decide to get comfortable, but soon I have to get up. Someone has rung the doorbell. During the week we don’t usually receive visits, so it seems a bit strange. They’re asking for Rich, so I open the building’s door. I stay at the door, so I don’t have to get up again. Besides, I’m very curious to see who’s coming.

It’s a friend of Rich’s. I’ve spoken to him a couple of times, but the truth is I don’t remember his name. He seems to know the house, although I don’t remember him ever being here. After greeting me, he’s gone straight to Rich’s room. I’m a bit surprised, but I imagine Rich had already made plans with him.

It seems I can finally relax, and since I have absolutely nothing to do, I’ve picked up a Java book and I’m going to try to learn a bit more.

Entering Data via Keyboard

The topic is quite simple, but before we get into it, it’s still necessary to learn some more theoretical concepts. All this information might seem a bit overwhelming at first, but little by little everything will make sense. As personal advice, I’ll tell you that it’s important to combine theory with practice. The exercises are enjoyable and I’d even dare say they’re entertaining. The important thing is to keep progressing and know a little more each day. Now it’s time to understand in general terms what a class is.

Introduction to the Concept of Class

When we work in our IDE we write our code within these lines:

public class Main {

        public static void main(String[] args){

                    Our code goes here.

       }
}

I’ll explain what those first two lines we see there mean; it’s very possible you’ve been wondering for a while why they’re there and what they’re for. In later topics we’ll go deeper and analyze in detail the concept of class. For now, it’s important that you understand that those lines are necessary for the code to identify that we’re working with a class and that this will be fundamental in object-oriented programming.

public class Main: In Java, a program is organized into “classes”. A class is like a blueprint or a recipe that tells the computer how to do something. When you write public class Main, you’re saying that you’re creating a new class called “Main”. The public means that this class is accessible from anywhere in the program.

When you start a project in Java, you need at least one class to act as a starting point, and it’s usually called “Main” (although it can have any name). This Main class is where the program execution begins.

public static void main(String[] args): It’s the main method (or “main”) that the system executes to start a program.

  • public: This means that the main method is accessible from anywhere in the program. It’s like an open door that allows other methods to call it.
  • static: This indicates that the main method belongs to the class itself, rather than to a specific instance of the class. In simple terms, you can call main without needing to create an object of that class.
  • void: This means that the main method doesn’t return any value. In other words, it doesn’t produce any result when executed.
  • main: This is the name of the method. It’s the main entry point for the program.
  • String[] args: This is a parameter that the main method receives. It’s an array of text strings that can contain arguments passed to the program when it’s executed. For example, if you run your program from the command line and type something after the program name, those “something” are stored in this array. For example, if you run java myProgram Hello World, then “Hello” and “World” would be stored in args.

You might find all this a bit strange to understand, but soon everything will start to make sense. In the following topics we’ll touch on these concepts in more depth. For now, let’s focus on learning to solve problems and understanding another series of basic concepts.

The Execution Order of a Program

To better understand this section, you need to understand the order in which our lines of code are executed in Java. The program executes from top to bottom. For example, if we create a variable on line 18 and try to assign it a value on line 17 (one line before), the program will return an error. On line 17, the variable hasn’t been created yet, so the program doesn’t know it exists yet. The only valid process is to first create a variable and then assign it a value.

The same happens when entering data via keyboard. It doesn’t matter if we have five thousand lines written; if on line 22 we’ve given the instruction that data must be entered via keyboard, the program won’t read the following lines until we enter something.

Once this small clarification has been made, we can now go into depth on this topic. The first thing we need is to know what a Scanner is and then how we apply it to our programs and applications.

Importance of Data Input in Interactive Applications

Data input is fundamental in any interactive application, as it allows users to provide the information necessary for the program to function. Here are some key reasons why data input is so important:

1.      User-Program Interaction

Data input allows direct interaction between the user and the program. Without this interaction, the software couldn’t adapt to the user’s needs and preferences.

For example, in a banking application, the user can enter their account number and PIN to access their financial information.

2.      Customization and Adaptation

Programs can be customized according to user input, offering a more relevant and personalized experience.

3.      Information Collection

Applications collect data through user input to perform calculations, store information, and make informed decisions.

4.      Control and Navigation

Data input allows users to navigate through different options and functionalities.

5.      Validation and Security

Through data input, applications can implement validation and security mechanisms, ensuring that only authorized users access certain functions.

6.      Feedback Collection and Improvements

Applications can include mechanisms for users to provide feedback, which is crucial for continuous software improvement.

Using the Scanner Class

In Java, a “scanner” commonly refers to the Scanner class from the java.util package. This class is used to read user input from the console or from other input streams, such as files. It allows reading different types of data, such as integers, floats, strings, etc.

To use scanner in Java we must write the following line above our main class:

import java.util.Scanner;

It would look like this:

import java.util.Scanner; 

public class Main {

       public static void main(String[] args) {
 
                    //our program code.

       }
}

Package Concept in Java

In Java, a “package” is simply a way to group and organize code. Imagine it’s like a folder where you store related files. Packages help us avoid confusion with class names and allow our code to be better organized.

A package can contain several things, such as classes, interfaces, and subpackages. For example, if you’re creating a program for an online store, you might have a package called “com.onlinestore” where you store all the classes related to your store.

To indicate that a class belongs to a package, the package keyword is used at the beginning of the class file.

For example:

package com.onlinestore; 

public class Product {

         // Product class code

}

In this example, the Product class belongs to the com.onlinestore package. This means that other classes in the same package can access it directly without needing to import it, while classes outside this package will need to import it to use it.

Once we’ve imported the Scanner package, we can continue writing the code of our program within our class.

Creating and Using a Scanner

To be able to enter data via keyboard, the first thing we must do is create a Scanner and it’s always done in the following way:

Scanner exercise = new Scanner(System.in);

In this case we’ve called our Scanner “exercise” but obviously it can be called whatever you prefer.

Once created, we need to call that scanner and we must do it exactly when we need data to be entered via keyboard. The program won’t continue executing until a value is entered via keyboard. The line of code we’re going to use to call that Scanner will depend on the type of data we’re going to enter.

Reading Different Types of Data

With Scanner, you can capture text strings, integers, floating-point numbers, boolean values and more, all with specific methods that guarantee precise and efficient reading. However, depending on the data type, we’ll need to use a different line of code to “call” the Scanner we’ve previously created.

Look at these examples:

int a = exercise.nextInt();

double a = exercise.nextDouble();

String a = exercise.nextLine();

boolean a = exercise.nextBoolean();

char a = exercise.next().charAt(0);

Be careful as they all have the same structure except in the case of char variables.

Practical Example:

Let’s look at an example, as it’s the easiest way to understand it. We need to create a program where two integers are entered. We’ll call them a and b. The program should ask us one by one to enter their values. Then, it will perform the multiplication of both values and show us the result in the console.

In the following code, we’ll see how we import the Scanner package, then create a Scanner called exercise, and finally call the Scanner at the exact moment we need data to be entered.

import java.util.Scanner;

public class Main {

          public static void main(String[] args) {


                     //We create the Scanner

                     Scanner exercise = new Scanner(System.in);

 
                     // We ask for the value of number a


                     System.out.println("Enter the value of number a");
                     int a = exercise.nextInt();


                     // We ask for the value of number b


                     System.out.println("Enter the value of number b");

                     int b = exercise.nextInt();


                     // We perform the operation of both variables and display them on screen 

                     System.out.println("The result of multiplying is " + (a*b)); scanner.close();

          }
}

Closing the Scanner

Closing the Scanner object is a crucial practice in Java to release the resources associated with data input. When you’re done using a Scanner, especially if it’s reading from System.in, you should close it with the close() method. This not only helps release memory, but also prevents potential security issues and resource leaks. Properly closing the Scanner ensures that the program handles system resources efficiently and responsibly. For example, at the end of your program, you can use scanner.close(); to properly close the Scanner object.

Summary of What We’ve Learned

Chapter Summary

In Java, a class is like the design of a building: it defines the structure and organizes the parts of the program. The Main class is where everything begins, that is, the program’s entry point. When we write public class Main, we’re saying that this class is accessible from anywhere in the code.

Within the Main class, the public static void main(String[] args) method is fundamental because it’s the first place where the program starts executing. Here’s an explanation of each part of this method:

public: This means that the method can be used from anywhere in the program.

static: Means that this method belongs directly to the class and not to an object created from the class.

void: Indicates that the method will not return any value.

main: It’s the name of the method that Java always looks for when starting a program.

String[] args: It’s an array that can contain arguments provided when the program is executed.

The main concept explained in this topic is the introduction of data via keyboard. For this we use the Scanner class. This class facilitates reading data such as numbers and text from the keyboard.

To use Scanner, first we need to “import” the class. Then, we create the Scanner itself, and after that we call it in the exact part of the program where we need it. Depending on the type of data we’re handling, the code we use to call the Scanner will be different. Finally, we must remember that it’s important to close the Scanner when finished, to release the resources it was using.

In summary, you now understand how a class works in Java and how to handle data input with Scanner. And if it’s still not completely clear, I now propose some exercises that will definitely clear up your doubts.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏