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)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.