Sum of two numbers by receiving value from keyboard
In this program we use two variables which receive value from the keyboard and add those values and sum of these numbers are stored in the third variable.
In this example we are using Scanner, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double etc. and strings.
It is one of the ways to read input in a Java program.
Syntax for scanner...
Declare the object and initialize with predefined standard input objectScanner sc = new Scanner(System.in);
String input
String name = sc.nextLine();
Character input
char gender = sc.next().charAt(0);
Numerical data input
byte, short and float can be read
using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
Xample:
File_name: Addition.java
For Compiling: javac Addition.java
For Execution: java Addition
Remember filename and class name must be the same
import java.util.Scanner;
class Addition
{
public static void main(String[] args)
{
int a, b, c=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers :");
a=s.nextInt();
b=s.nextInt();
c=a+b;
System.out.println("Sum: "+c);
}
}
OutPut:
Enter any two numbers :
10
20
Sum: 30
That's it, I hope it is useful.
Thanks For reading.
No comments:
Post a Comment