Addition of Two Numbers by User Input
Here, you will learn to program Addition of two numbers in Java by user input. This program enables the user to adding two numbers in java by using 3 different methods.
1. using command line arguments.
2. using Scanner Class
3. using Buffered readers
Addition of two Numbers in Java using Command Line Arguments
This program enables the user to adding two numbers in java using command line arguments.
1 2 3 4 5 6 7 8 9 10 | //Addition of two number in java using Command Line Argument class Add { public static void main(String str[]) { int a,b,c; a=Integer.parseInt(str[0]); b=Integer.parseInt(str[1]); c=a+b; System.out.println("Addition of " + a +" and "+ b +" is = " + c); } } |
Output
Addition of two Numbers in Java using Scanner
Let’s do the Sum of Two Numbers program by using scanner class, to get input from the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //Addition of two Numbers in Java using Scanner import java.util.Scanner; class AdditionWithScanner { public static void main(String str[]) { int a,b,c; System.out.println("\nEnter the value of a and b "); Scanner in = new Scanner(System.in); a = in.nextInt(); b = in.nextInt(); c=a+b; System.out.println("Addition of " + a +" and "+ b +" is = " + c); } } |
Output
C:\CodeRevise\java>javac AdditionWithScanner.java
C:\CodeRevise\java>java AdditionWithScanner
Enter the value of a and b
7 9
Addition of 7 and 9 is = 16
Addition of two Numbers in Java using Buffered readers
Let’s do the Sum of Two Numbers program by using Buffered Reader, to get input from the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.io.*; import java.lang.*; class additionByBR{ public static void main(String args[]) throws IOException{ InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); System.out.print("Enter two numbers : "); String s=br.readLine(); int a=Integer.parseInt(s); String t=br.readLine(); int b=Integer.parseInt(t); int c=a+b; System.out.println("SUM = " + c); } } |
Output
C:\CodeRevise\java>javac additionByBR.java
C:\CodeRevise\java>java additionByBR
Enter two numbers : 12
34
SUM = 46
Check out our other Java Programming Examples