Copyright

Java: Add Two Numbers Taking Input from User

Lesson Transcript
InstructorMartin Gibbs

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 has options to enable the user to input numbers for addition operations. Review the process to enable user input for adding numbers, complete with the full code and the steps to check for errors. Updated: 08/24/2023

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.

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

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

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

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

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.

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.


Java exception output


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.


Java add numbers error checking output


Eventually, the data entry is complete and the numbers are added together.

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

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

Resources created by teachers for teachers

Over 30,000 video lessons & teaching resources‐all in one place.
Video lessons
Quizzes & Worksheets
Classroom Integration
Lesson Plans

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.

Jennifer B.
Teacher
Jennifer B.
Create an account to start this course today
Used by over 30 million students worldwide
Create an account
close