User Input in Java for Different Types of Variables

More on Data Types and User Input in Java: Video Lecture 4

We have been discussing preliminaries of Java Programming language so far. If you have watched all the previous videos we made and completed the associated exercises, it is time to talk more about data types and user input in Java programming language.

The Video: Data types and user input in Java

In the previous video, we introduced how to get a double user input in Java. In the following video, we will see how we can write a code to get “input” for several different types of variables.

Variable Types and User Input in Java

The Final Program Used in the Video

We are providing the final program used in the video below. The program engages in a conversation with the user. Through the code, you will get an idea of user input in Java for several types of variables. Save the file as MyProg.java.

import java.util.Scanner;

class MyProg{
  public static void main(String[] args){
    String name;
    byte age;
    double income;
    
    Scanner sc = new Scanner(System.in);
    System.out.println("What is your name");
    name=sc.nextLine();
    System.out.println("Hi, "+name+" how old are you?");
    age=sc.nextByte();
    System.out.print("If you do not mind, "+name+", ");
    System.out.println("what is your monthly income?");
    income=sc.nextDouble();
    System.out.print("Great! "+name+", ");
    System.out.print("you are "+age+" years old, ");
    System.out.println("and you earn "+income+" each month.");
    
  }
}

Exercise

Extend the program we wrote in the video such that, in the final message, the computer provides the annual salary of the user instead of the monthly wage. That is, the user will provide the monthly salary, and the program will calculate and display what the yearly salary will be.

Comment

We will cover mathematical operations in a future video. To stay in touch, please subscribe to Computing4All.com. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Monika Akbar. I am the other instructor in this video lecture series.

Dr. Hossain has already explained two types of variables — integers and “double” numbers — in the previous lectures. Integers are round numbers. We write the integer data type as “int”. Doubles are numbers that have decimal values. From the last video lecture, you already know how to get input from the user.

Today, we will discuss a few more variable types, and we will learn how to get “user input” for different kinds of variables.

The program involving user input in Java

We will write a simple program, in which we will declare a few variables of different kinds. I will explain the differences between the variable data types on the way. Let us go to my desktop computer. I will share my desktop with you now.

The program, I will write today, is quite simple. For clarity, it is better if I show you the program output right now and then I will show you how I coded the program.

The program engages in a conversation with the user. At first, the program asks for the name of the user. Then the program will ask the user for age. Afterward, the program will ask to provide the monthly salary of the user. Notice that the program asks the second and the third question addressing the user by name. The questions have a conversation style. Today, we will see how to write this program.

The file I am using is MyProg.java. Therefore, the class is MyProg. I am writing my main method.

Inside the main method, I will write my code.

The variable: name

At first, I will declare the variables we will need for the program. As I said, the program will prompt for the name of the user. After the user provides a name, the program will greet the user using the name. That means the program needs to remember the name of the user. That is, the program needs a variable to remember the name. A name may have an arbitrary number of letters in it. For natural language inputs that may contain any number of letters or symbols, Java has a particular data type. The data type is called String. A String can hold practically any text, such as a name, or an address, or an essay.

For the name, I will use a String variable. I am writing the data type, which is String, then I am typing the variable name, which is the word “name”, and then I am writing a semicolon. The variable “name”, will capture the name of the user.

For the name, I will use a String variable. I am writing the data type, which is String, then I am typing the variable name, which is the word “name”, and then I am writing a semicolon. The variable “name”, will capture the name of the user.

The variable: age

The second variable I need is for the age of the user. I can use “int” or I can use double, but I would use another data type here to store the age of the user. The other data type, which is also a number type with a round value, is called “byte”. The byte data type can hold numbers that are no larger than 127 and no lesser than negative 128. Since age is most likely to be less than 128, I will use a byte data type to remember the age of the user. Note that we could use an integer too, but I wanted to introduce this new variable type to you. This is why we are using byte for the age. I am giving the variable a name “age”. Then I type a semicolon. I should again mention that byte store round numbers. That is the age has to be a round number, without any decimal point.

The variable: income

The third variable we will use is to store the income of the user. Income can be a large number. Therefore, I will use double. I am typing double income; then I put a semicolon.

Scanner for user input in Java

We now have three variables: name, age, and income. Notice that each of these variables has a different data type. Now, we will create a Scanner just like we did in the previous video. Recall from the last video that we have to include the Scanner class with our program so that this program can use the functionality written inside the Scanner class. At the top of my code, I am adding import java.util.Scanner and then putting a semicolon.

Now, we can create a Scanner object that will help us get user input of any data type. Today, I will give the Scanner object the name sc. I am typing Scanner sc= new Scanner (System.in);

sc is an object variable of type Scanner. sc would help us get user input. In the last video, we provided some explanation on this line.

Asking the user for her/his name

Now, I am going to write a question using System.out.println. That is, the program will ask this question to the user. Within System.out.println, I am writing, “What is your name?” At this point, if we compile and run the program we will just see that the program is printing “What is your name?” Then the program will end immediately, given that we haven’t told the computer to do anything yet.

After “What is your name?” is printed on the terminal, we want the program to get input from the user. That is the user will Type her or his name using a keyboard and the program should save the name in the variable we have to store name. We know that we have to use our Scanner object sc here.

Getting a String user input in Java using a Scanner object

We need to write the variable name in the left side, and then on the right side, we need to write whatever scanner functionality we want to write to get the input from the user. The right side of the assignment operator is always executed first. In the left side, you only keep one variable, in this particular case, the variable “name”. In the right side, I am typing sc dot nextLine(). That is “sc”, the Scanner object, has the capability to read a line of text. The capability is summoned by the nextLine() method. Now the right side of the assignment operator will be executed first, which practically will keep waiting until the user types and enters her or his name. Once the user types some text, the sc.nextLine() method captures it and creates a string. The assignment operator sends the string captured by the sc.nextLine() method to the “name” variable in the left side.

Asking for the age of the user

Now that the program remembers the name string the user provided in the name variable, the program can address the user by her or his name. I am going to write the next question that the program will ask, using a System.out.println method. The next question is, How old are you? This is great but I would like to include the name of the user in this question. For example, Hi John, How old are you? To do that, we will somehow include the name of the user in this System.out.println method.

Remember from the last video that, whatever we want to print “as it is” goes inside the quotations. To print the variable content, we directly provide it outside the quotations. We concatenate quotations parts with the variables using a plus symbol.

Since I want to say, “Hi”, I put Hi inside the quotation. Then I want my program to say, the name of the person who is running the program. The name of the person is saved in the String variable name. Therefore, I type the plus symbol concatenate the name with Hi. Then I write another plus symbol to concatenate the last part where the program will say, “How old are you?”

Partial program

Let us compile the program and run it to see what happens.

The program asks the user for her name. The user types her name, Jane Doe, and presses the enter button. Then the program addresses the user by name, saying “Hi, Jane Doe, how old are you?” Then the program ended its execution. That is because we did not write anything in the code to get user input for age. Let us go back to the code and work on the rest of the code.

Getting the age of the user using a Scanner object

Remember that the variable age is a byte data because we declared it as a byte. I am typing age equals, then on the right side, I will write something using the Scanner object to get a byte size number from the user. The command is nextByte. I type sc.nextByte();

The age variable will contain the age provided by the user.

Asking for income information of the user

Now, the next line, within System.out.print I am writing “If you do not mind,” in quotations and then I append the name of the person, and then I append a comma only. Notice that I have use System.out.print not System.out.println here. After this line is executed, there will be no new line. Whatever I will print next will be printed in the same line in the output.

Now I am writing a System.out.println, inside which, within the quotations, I am writing “what is your monthly income?” After this is printed, the prompt will go to the next line because we have used System.out.println, not System.out.print.

Getting the income of the user using a Scanner object

Anyway, at this point, the program should prompt for income. To get user input for income, we write income=sc dot . Now notice that we declared the income variable as a double. Therefore, we will write sc.nextDouble(); to get a double input from the user. This line will get the double input from the user and put it inside the income variable.

Displaying everything

Now that the program has everything, name, age, and, the income of the user. The program can display any message using these information pieces.

I will write two System.out.print methods and one System.out.println method to display what we want to tell the user.

We will say, “Great! “, then we want the program to state the name of the user, so we append the name varaible.

In the next System.out.print method we want our program to say, you are this many years old. In the “this many” part, we want the program to write the age that the user provided.

Finally, in a System.out.println we will write “and you earn this much each month.” In place of this much, we want the program to print the income that the user provided, which is stored in the income variable.

I use a System.out.println to make sure that after the last thing printed on the terminal, the command prompt goes to a new line.

Output of the program

Let us save the file MyProg.java. Compile it and then run it.

Notice, how it is working. The program asks the user for her name. The user provides the name, Jane Doe. Then, in the next question, the program uses the name of the user and asks for her age. The user provides her age. Then the program uses the name again for the third question. This time, it asks the user for her monthly income. The user provides a monthly income of, say 20000.
After the user enters the income, the program prints this nice message. Great! Jane Doe, you are 20 years old and you earn 20000 each month.

A limitation of the program

While this is a nice program, it has some flaws. It is always good to know the limitations of your programs. The more you know the limitations, the better you can make it foolproof. We will not make it foolproof today because we have not yet covered all the necessary topics to be able to make a program foolproof. Over time, we will learn more items, such as how to apply conditions and looping, that will help us make a program bug-free.

As I said earlier, the data type, byte, cannot hold any number greater than 127. If there is a lucky person in the world who is using the program and has age greater than 127, then the program will behave abnormally. Let us see.

Sample output to demonstrate the limitation

Let us say, the name of the person is John Doe. John types his age, which is 128. As soon as John hits the enter button after typing his age, the program shows an error and terminates. Notice that the error states “Value out of range. Value:”128″”

Every variable has a limit. On the screen, we have provided a list of data types and the range of numbers each data type supports.

Notice that byte supports numbers between negative 128 to positive 127. A short data type supports numbers between negative 32,768 to positive 32,767. Data types int, long, float, and double support larger and larger ranges of numbers. float and double have an extra power; they can handle decimal numbers, while byte, short, int, and long are only for round numbers.

Please visit the supporting page on Computing4All.com for today’s lecture for additional resources.

Final remarks

We always tell our students at the bachelor’s level, many of whom are just starting to learn a programming language, to have patience and keep practicing. Practice makes everyone perfect.

The learning principle is the same for everyone, whether the person is self-learning a programming language, or the person is learning it in a course. If you are learning all by yourself and watching this video as additional material, please know that we are making these videos, especially for you, because we know that you have little to no help. My suggestion is, please please please practice while you are watching our programming videos. After practicing what we cover in the videos, please go beyond and above to write another program of your choice, using the knowledge you gained so far.

If you find our videos informative, please give us a thumbs up, subscribe to Computing4All.com, and our YouTube channel. If you have any question, please send us a message via Computing4All.com or by simply writing a comment in the Comments section below. Thank you for watching the video.

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 *