Java: Add Two Numbers Taking Input from User

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Java: Generate Random Number Between 1 & 100

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 User Input
  • 2:04 Full Code
  • 2:30 Error Checking
  • 4:15 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

Most programs take input from users and perform actions on those values. This lesson will show how to take user input in Java, add the values together, and check for errors.

User Input

The first step in taking user input is to import special functions into our program. Java runs fairly lean, meaning that it doesn't include all functions in all projects. You can import only the ones you need. This reduces run-time and makes code cleaner. We'll be importing the utility Scanner, which allows input/output. Scanner is actually part of the overall Java util (utility) package. You could just import all of the util package, but since we're only taking user input from the keyboard, we will use the following statement at the top of our program:

import java.util.Scanner;

Now that we've imported the utility, we can begin to take user input. But, before we can do that, we need to create a variable to store the values entered by the user. The Scanner utility is actually a Java class, so we can simply create an instance of that class. This will be used to read in the values, which you can see play out below.

public static void main(String[] args) {
  Scanner readme = new Scanner(System.in);
}

Next, we'll need to ask for user input. Also, we'll need to declare variables to hold the values of the numbers. We'll need one each for the input as well as one for the total of the two numbers. You'll notice that we're using the double data type, which allows us to have really big numbers. Integer, float, short, or long are valid here, too.

The last two lines of the following code are the heavy-lifters of our program. They actually read the user input and store it in our variables. The instance variable can invoke a method within the Scanner class called nextDouble( ), which you can see playing out below.

System.out.println("Enter Two Numbers " + "(Press Enter after each):");
//two variables to hold numbers
double n1, n2, n3;
n1 = readme.nextDouble();
n2 = readme.nextDouble();

Again, we're taking input as a double. Scanner provides methods for other types, such as nextInt( ), nextLong( ), or nextFloat( ). The syntax is the same as above.

The last step of our program is to actually do the math. We created the variable n3, so we can save our addition to that variable and display the output.

n3 = n1 + n2;
System.out.println("Total = " + n3);

For this program, that is all we need for it to work.

Full Code

As you can see below, here's the full code of our program so far. We still need to check for errors, but we at least have a fully functioning program at this point.

//import java.util.Scanner;
public class Inputfunctions {
  public static void main(String[] args) {
   Scanner readme = new Scanner(System.in);
   System.out.println("Enter Two Numbers (Press Enter after each):");
   //two variables to hold numbers
   double n1, n2, n3;
   n1 = readme.nextDouble();
   n2 = readme.nextDouble();
   n3 = n1 + 2;
   System.out.println("Total = " + n3);
  }
}

When we run the program, we're prompted for two numbers. Below is the output from that run, including the final output.


Java add numbers output


For this run, we entered valid numbers. But what would happen if we entered text or some other non-numeric value?

Error Checking

Currently, our code has no error-checking. It assumes that the user will enter valid numbers. You can enter an integer into a double, or a float into a double; it just adds the decimal and a zero when you do that. But, the problem is, you can't put in a byte or a Boolean into an integer field. The code that you're looking at right now shows what will happen if you enter something other than a number. As you can see, it results in a build failed notification, among all the other things.


Java exception output


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support