DEV Community

Edwin Torres
Edwin Torres

Posted on

Java Input and Arithmetic

This tutorial is a simple Java program that asks the user for two numbers, adds them together, and outputs the result.

  1. Create a new Java project in VS Code.
  2. Create a new Java file named AddExample.java, where you will type the code below.
  3. Import the Scanner class. This built-in Java class lets you accept input from the user.

    import java.util.Scanner;
    
  4. Start the class definition. It must match the filename. The curly bracket indicates the start of the program.

    public class AddExample {
    
  5. 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) {
    
  6. 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);
    
  7. Output a line that asks the user to enter two numbers.

        System.out.print("Please enter two numbers: ");
    
  8. Use the Scanner object to read in two integers and store them in two integer variables x and y.

        int x = s.nextInt();
        int y = s.nextInt();
    
  9. Use arithmetic to add x and y and store the result in an integer variable z.

        int z = x + y;
    
  10. Output the result.

        System.out.println("The sum is " + z);
    
  11. Close the main method definition with the ending curly brace.

      }
    
  12. Close the class definition with the ending curly brace.

    }
    
  13. 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)