Tuesday, 22 September 2015

How to get Input from the user in JAVA

JAVA
   The programs should interact with the user and should provide services for users (For taking the addition program as example user only need to give values to add then program will automatically calculate and print the result).
   In Java there are various methods to get the input from the user.
For getting input from the user we need scanner functions to scan the input and perform operation.
Java provides many functions and methods for scanning the inputs from the user. Each of them is specific and different.
The first method is to use BufferedReader class. It is a simple and basic method used for getting input and store in a variable.
Just read the following example:
 
import java.io.*;
class add
{
public static void main(String args[])
{
int a, b, c;
System.out.println(“Enter the values of A and B
to add:”);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println(“The result c=”+c);
}
}
 
This program allows user to enter different values to add.
For getting input or scanning the input from the user first create an object for BufferedReader class (br) and InputStreamReader (in) class, by the statement
“BufferedReader br=new BufferedReader(new InputStreamReader(System.in));”
(Object creation is a very basic and essential thing in JAVA programming language. Object is created for many purposes, in this program for scanning purpose two objects are created.)
After that we have to convert the user inputs to the required datatypes, because java language takes any value as a string (Set of characters), we have to convert that string to required datatypes using the following statements.
“ a=Integer.parseInt(br.readLine());
  b=Integer.parseInt(br.readLine()); ”
In the above statement Integer is a class, parseInt is a method to convert the integer type data into String type data.
Because java only supports string data types we have to convert the other data types into String, thus we use this conversion method.
  Thus normal addition operation is performed by getting input from the user.
Now compile and run this program so that  getting input from the user and performing addition operation is performed.
See here how to compile and run the Java program.
How to run java program