Getting user input in Java can be intimidating for beginners. With practice, it can become easy.

Getting User Input and Making a Calculator Using Java: Video Lecture 3

I am writing this article in support of the video we made on the topic — Getting User Input in Java. The video helps new learners by providing explanations on how to develop a simple calculator program. The user of the program types on the keyboard to enter two numbers. The program captures the two numbers the user provides and then it applies addition, subtraction, multiplication, and division operations on the numbers.

Why a Programmer Needs to Know About User Input

A programmer needs to know about user input due to the tremendous need for user input in many modern day software pieces. Consider the calculator program you have on your phone or laptop. It requires your input to apply mathematical operations. Consider editor software like MS Word. We type on the keyboard, and MS Word saves what we type. MS Word helps us format what we want to print.
Consider the Google Maps App on your smartphone. You write a destination address, and the software provides you directions to the destination. That is, the program reads the address you provide.

Therefore, getting input from the user is quite common in computer programs.

The Video: Getting Input from the User, for a Calculator Program, Using Java

Getting input from the user is an essential part of programming. It can be intimidating for beginners. With some practice, writing Java code to get input from user becomes quite mundane over time.

Getting User Input from a Calculator Program Written in Java

The Final Program Used in the Video

In the video, we only covered how to get user input of double data type using a Java Scanner object. The programmer can use nextInt() instead of the nextDouble() method to get an integer from the user. The program that we came up with, for double numbers, in the video is provided below. Save the program in a file named MyProg.java.

import java.util.Scanner;

class MyProg{
    public static void main(String[] args){
        double num1;
        double num2;
        double res;
        
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the first number:");
        num1= scan.nextDouble();
        System.out.println("Enter the second number:");
        num2= scan.nextDouble();

        res=num1+num2;
        System.out.println("Summation: "+res);
        res=num1-num2;
        System.out.println("Subtraction: "+res);
        res=num1*num2;
        System.out.println("Multiplication: "+res);
        res=num1/num2;
        System.out.println("Division: "+res);
    }
}

Exercise

Write a program that does the following items.

The program asks the user for three double numbers and displays (a) the result of the summation of the three numbers the user provided and (b) the result of multiplication of the three numbers.

Comment

You will see more of user input in our future videos. To stay in touch, please subscribe to Computing4All.com. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Shahriar Hossain. I am here today to help you practice more on variables. We will build a Calculator program today using Java.

From the last video lecture, you know how to add two numbers and how to subtract one number from another. In the exercise, which I provided on Computing4All.com, I asked for multiplication and division as well. I will extend the concept that I described in the previous class. I will write the code of the last lesson and also do the exercise, which is the inclusion of multiplication and division. That should be good enough for a quite primitive calculator.

One item is that in our code, we are hard-coding the numbers so far. That is, every time we change the numerical values of the variables, we need to compile the code to generate the class file because of the change. In an ideal program, the program should ask the user for two numbers, and then the program should do whatever mathematical operations it is supposed to do.

I will now share my screen with you so that you can see how I write the program. I will keep explaining on the way.

The starting of the code

Suppose, the name of the Java file I am working on is MyProg.java. Therefore, the class name has to be MyProg. The scope of the class is within a set of curly braces. I will now write the Main Method. I am writing the Main Method public static void main and the parameters. The Main Method has a scope too, within a set of curly braces. We will write the instructions inside the curly braces.

Please note that we are building a calculator program. Therefore, we need two numbers held in two variables. These two variables will be the operands of addition, subtraction, multiplication, and division. We are not working on any sophisticated calculator program today. The calculator we will build will only have the ability to add, subtract, multiply, and divide.

Declaring the variables

Let us declare two Double variables. We already know how to declare two Double variables from the last lecture. The names of the two variables that will become our operands are num1 and num2. I declare the first one by stating “double num1;”, and the second one by “double num2;”. I should mention again that we have to put a semicolon at the end of each instruction. The line public static void main is not an instruction. It is defining where is the starting of the program is. Therefore, public static void main does not have a semicolon at the end. Over time, we will see that there are statements in Java for which we do not put semicolons.

An Instruction is a unit task. In general, each instruction inside the main method must have a semicolon at the end.

Anyway, I declare another double variable named res, in which I will put results of the mathematical operations addition, subtraction, multiplication, and division.

Now we will put some values inside num1 and num2. Let us write instructions to put 25 inside num1 and 12 inside num2.

So far, we declared all the variables and initiated num1 and num2 with operands. I will first add the two numbers in num1 and num2 and put them in the “res” variable.

The assignment operator

Note from the previous lecture that, in a line, with the assignment operator, the computer executes the right side of the assignment operator first. Whatever the value of the right side is, the computer copies the value to the variable in the left side. The left side cannot have anything other than one variable.

Summation

When executed, res should contain the summation result. Let us print the summation result on the terminal, as we did in the previous video lecture. If we run and compile the program, we should see the value of res, which is the addition of num1 and num2, on the terminal.

To be exact, the output will be “Summation: 37”

Subtraction

Now, we would like to do the subtraction. Notice that after printing the summation result, we can reuse the “res” variable for any other operation. We will subtract. So, we write “res=num1-num2;”

We write a System.out.println instruction to print the subtraction result.

Multiplication and division

Similar to addition and subtraction, let us write the code for multiplication and division. Each of the mathematical tasks includes one line of instruction to do the mathematical operation and one line to display the result.

After you have written the code for all four operations, compile and run the program. We can see that results of all the operations — addition, subtraction, multiplication, and division — are correctly printed on the terminal.

Hard-coding is not a good idea, in this case

While I like the code so far, notice that for a pair of new numbers in num1 and num2, we have to recompile the code and run again, which is not a good idea for software development. The user does now know how to compile or change the code. Therefore, we need to modify the program in such a way that the program asks the user for two numbers, and then the program outputs the results of the mathematical operations carried over the two numbers that the user provided.

Assigning values directly in the code like the ones we have done here, is called hard-coding. Instead of hard-coding the numbers we will change the code so that the program asks for input to the person who will run the program.

Getting user input in Java may not look straightforward

Getting input from the user is not entirely straightforward. I will introduce a few new items regarding getting information from the user. The items might not make much sense at this point because we are still not familiar with methods, classes, and objects. We will be using the new items to get input from the user. Much later, when we learn advanced topics, we will understand the inner functionality.

Java Scanner

Anyway, to enable your code to get inputs from the user, you need to use the Scanner class, which we are not familiar with at all. At the beginning of the code, even before the first line, now we have to write “import java.util.Scanner;”. For now, the explanation that might make sense is the following — this particular class “Scanner” has the functionality written in it that allows a program to get user inputs. Through this line, your program is telling the Java Virtual Machine to import that functionality of scanning numbers from users.

Now, instead of hard-coding the numbers to num1 and num2, we will ask the user to enter two numbers by typing on the keyboard. Our program will assign the two numbers that the user provided to num1 and num2.

Before the assignments, we will have to create a scanner object. To create a scanner object named “scan”, I am writing this line. We have not discussed objects yet. Therefore, it will be hard for you to understand this line at this point. For now, you will have to trust the following explanation: this line creates a scanner object named “scan” that is capable of capturing the input the user will type on the keyboard.

Getting user input in Java: The nextDouble() method

Previously we assigned 25 to num1 and 12 to num2. These two lines must change because we are not hardcoding anymore. Instead, we will tell the computer to copy the number that the object “scan” captures to the variable num1. In the right side of the assignment operator of num1, we write scan.nextDouble();

That is, the object “scan” will wait for the next double number entered by the user. Once the user types a double number and hits the enter button, the “scan” object will send it to the num1 variable. If the user does not type a number and does not hit the enter button on the keyboard, then the program will remain waited at that point.

Now let us do the same for num2. In the right side of the assignment of num2, we will write scan.nextDouble();

In this line, the program will wait for the second number to be entered by the user.

Now, the program is ready. Save the MyProg.java, and compile it.

User input on terminal

Now let us run the program. Notice that the program is not displaying anything. Instead, it is waiting, which looks like the program is stuck. Actually, it is waiting in the line “num1=scan.nextDouble();” It is waiting for the user to type a number and hit enter. Now, as the user, I am typing 22.4, and then I press the enter button.

Notice that the program is again waiting. It is because now the execution is in the line “num2=scan.nextDouble();” The computer is waiting at “scan.nextDouble()” for the user to enter another number, which the computer will put in variable num2.

Therefore, as the user, I am typing 2.0 and then I will hit the enter button. As soon as I will hit the enter button the scan.nextDouble() will capture the value 2.0. Then the assignment operator will send 2.0 to num2.

Once num1 and num2 are ready, the computer will execute the rest of the lines in a jiffy. That is, the summation, subtraction, multiplication, and division results will be printed as soon as the num2 variable receives a value from the user. Now, I will hit enter, and the program will print all the results.

The user can run the program again and again. Each time the program will wait twice for two variables, num1 and num2.

Prompting for user input

One thing that I would like to include in the program is a message on the terminal before the program starts waiting for num1. I would like to add System.out.println and then write “Enter the first number: ” inside the parentheses inside quotations.

Similarly, before the scanner waits for the second input from the user, I would like to print on the terminal “Enter the second number: ” using a System.out.println method.

Save MyProg.java and compile it. Run the program. Now notice that the program prints “Enter the first number: ” before it starts to wait for the first input. Now I enter 20.2. The program now received the first input. Before it started to wait for the second input, it printed “Enter the second number: “. Now I enter 2.0. The program prints all the results.

Notice that this version of the program is more user-friendly since the program is communicating with the user by providing guidelines like, Enter the First number, or Enter the second number.

Conclusion

If you have any question, or if you are struggling to compile and run any of the programs we discussed so far, please do not hesitate to contact us via Computing4All.com or by leaving a comment in the comments section.

Thank you for watching the video. We will be coming back soon with another video in this video lecture series. To stay in touch, please subscribe to Computing4All.com and to our YouTube channel.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *