Martin has 22 years experience in Information Systems and Information Technology, has a PhD in Information Technology Management, and a master's degree in Information Systems Management. He is an adjunct professor of computer science and computer programming.
Java: Add Two Numbers Taking Input from User
Table of Contents
ShowThe 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.
import java.util.Scanner;
public class Main {
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.
To unlock this lesson you must be a Study.com Member.
Create your account
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 Main {
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 + n2;
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.
![]() |
For this run, we entered valid numbers. But what would happen if we entered text or some other non-numeric value?
To unlock this lesson you must be a Study.com Member.
Create your account
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.
![]() |
The next code block shows how we can make sure the numbers entered are valid. We'll make use of a 'while' loop that will continuously process until a valid number is entered. The Scanner class also has another method, hasNextDouble( ) and corresponding methods for integer and float, that lets us know if the value is actually a double.
Our while loop will run if the input value is not a double. The exclamation point (!) in the while statement tells Java to process if the readme value is not a double. It's an inversion of the value. When the value is not valid, we display an error. This will continue forever until the user enters a valid number.
Take special note of the next( ) function after the warning. This gives the user another attempt at entering a valid number. If they don't, the loop simply repeats, and they try again until they get it right. Check out the following code to get a good idea of how all this plays out.
public class Main {
public static void main(String[] args) {
Scanner readme = new Scanner(System.in);
System.out.println("Enter Two Numbers (Press Enter after each):");
while(!readme.hasNextDouble()) {
System.out.println("Try entering a number");
readme.next();
}
double n1, n2, n3;
n1 = readme.nextDouble();
n2 = readme.nextDouble();
n3 = n1 + n2;
System.out.println("Total = " + n3);
}
}
}
And if we enter bogus data, it will keep telling us to enter a valid number, which you can see on the next set of code here.
![]() |
Eventually, the data entry is complete and the numbers are added together.
Now we can look at the final output, which has error checking and adds the two numbers, which you can see below. There are comments/notes within the code. As programmers we should always be sure to read those notes, as they often contain very helpful information!:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//declare and initialize numeric variables
//for use in the program
double n1 = 0, n2 = 0, n3 = 0;
Scanner readme = new Scanner(System.in);
System.out.println("Enter The First Number (Press Enter After It):");
//initial the state this variable showing that the value has not been successfully read
boolean valueSuccessfullyRead = false;
// while the value has not been successfully read
while (!valueSuccessfullyRead) {
// check if the next input value is a double
if (readme.hasNextDouble()) {
// if the next input value is a double, read it and record that it has been successfully read
n1 = readme.nextDouble();
valueSuccessfullyRead = true;
} else {
// if the next input value is not a double, read but do not store it
eadme.next();
}
// if a double value has not been successfully read, print this prompt before the loop repeats if (!valueSuccessfullyRead) {
System.out.println("Try entering a number");
}
}
System.out.println("First Number Read. Enter The Second Number (Press Enter After It):");
//initial the state this variable showing that the value has not been successfully read
valueSuccessfullyRead = false;
// while the value has not been successfully read
while (!valueSuccessfullyRead) {
// check if the next input value is a double
if (readme.hasNextDouble()) {
// if the next input value is a double, read, and record that it has been successfully read
n2 = readme.nextDouble();
valueSuccessfullyRead = true;
} else {
// if the next input value is not a double, read but do not store it readme.next();
}
// if a double value has not been successfully read, print this prompt before the loop repeats
if (!valueSuccessfullyRead) {
System.out.println("Try entering a number");
}
}
n3 = n1 + n2;
System.out.println("Total = " + n3);
/*
NOTE: The while loops above are virtually identical and repeated blocks of code.
They could easily become a single JAVA method which returns an input double value. That would be a more 'proper' and 'professional' implementation of this programming logic. You will learn more about JAVA methods in a later lesson.
*/
}
To unlock this lesson you must be a Study.com Member.
Create your account
Let's take a few moments to recap some of the important information that we learned about. With any programming language, there are multiple ways to solve a given problem. We covered the method of receiving user input from the keyboard. To do this you need to import the Scanner utility, which allows input/output and is actually part of the overall Java util (utility) package. We then scan in two numbers. In our case we used double, but these could have been integers. Also, we made sure to test for a valid number so the program wouldn't crash.
To unlock this lesson you must be a Study.com Member.
Create your account
Register to view this lesson
Unlock Your Education
See for yourself why 30 million people use Study.com
Become a Study.com member and start learning now.
Become a MemberAlready a member? Log In
BackResources created by teachers for teachers
I would definitely recommend Study.com to my colleagues. It’s like a teacher waved a magic wand and did the work for me. I feel like it’s a lifeline.