Java add two numbers from console input

Program will take as input two numbers a and b and find and print c which is the sum of a and b.

import java.util.Scanner;

public class MainAddTwoNumbers {
    public static void main(String[] args) {
        // Use 'try' to close Scanner and release taken resources.
        // Connect the scanner to System.in (keyboard)
        try(Scanner in = new Scanner(System.in))
        {
            System.out.println("Please enter two numbers to be added: ");

            int a = in.nextInt();
            System.out.println("You entered integer a: " + a);

            int b = in.nextInt();
            System.out.println("You entered integer b: " + b);

            int c = a + b;
            System.out.println("Result of a+b: " + c);
        }
    }
}

Output:

Please enter two numbers to be added: 
6
You entered integer a: 6
5
You entered integer b: 5
Result of a+b: 11

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.