This tutorial is a simple Java program that asks the user for two numbers, adds them together, and outputs the result.
- Create a new Java project in VS Code.
- Create a new Java file named
AddExample.java
, where you will type the code below. -
Import the
Scanner
class. This built-in Java class lets you accept input from the user.
import java.util.Scanner;
-
Start the class definition. It must match the filename. The curly bracket indicates the start of the program.
public class AddExample {
-
Inside the class definition, declare a main method. This method is the first method that the Java interpreter calls.
public static void main(String[] args) {
-
Inside the main method definition, create a Scanner object named
s
. This object will accept input from the user.
Scanner s = new Scanner(System.in);
-
Output a line that asks the user to enter two numbers.
System.out.print("Please enter two numbers: ");
-
Use the Scanner object to read in two integers and store them in two integer variables
x
andy
.
int x = s.nextInt(); int y = s.nextInt();
-
Use arithmetic to add
x
andy
and store the result in an integer variablez
.
int z = x + y;
-
Output the result.
System.out.println("The sum is " + z);
-
Close the main method definition with the ending curly brace.
}
-
Close the class definition with the ending curly brace.
}
Now run your program to see the result.
Congratulations!
You have written a Java program to accept two numbers from the user, add them, and output the result.
Thanks for reading. 😃
Follow me on Twitter @realEdwinTorres
for more programming tips and help.
Top comments (0)