Monday, 12 September 2011

Change the user input to integer

Isn't it a very tedious job to enter the values each time before the compilation in the method itself. Now if we want to enter an integer value after the compilation of a program and force the JVM to ask for an input, then we should use Integer.parseInt(string str).
As we know that JVM reads each data type in a String format. Now consider a case where we to enter a value in  int primitive type, then we have to use int x = Integer.parseInt("any String") , because the value we have entered is in integer but it will be interpreted as a String so, we have to change the string into integer. Here Integer is a name of a class in java.lang package and parseInt() is a method of Integer class which converts String to integer. If we want to enter a integer in a method or class using keyboard, then we have to use a method parseInt().
In this program we are going to calculate a area of a rectangle by using two classes named Rectangle and EnterValuesFromKeyboard. In the first class we have used two methods, show(int x, int y) and calculate(). First method show() is taking two variables as input and second method calculate() calculates the area of a rectangle. In the second class which is also our main class we declare a will declare our main method. Inside this method we will create a object of a Rectangle class. Now we ask the user to input two values and stored those values in the variables. These entered values will be changed into integer by using parseInt() method. Now these variables are passed in the method show() and the area will be calculated by calculate() method. These methods will be called by the instance of Rectangle class because it is the method of Rectangle class.
Here is the code of the program
class Rectangle{
  int length, breadth;
  void show(int x, int y){
  length = x;
  breadth = y;
  int calculate(){
  return(length * breadth);
public class EnterValuesFromKeyboard{
  public static void main(String[] args) {
  Rectangle rectangle = new Rectangle();
  int a = Integer.parseInt(args[0]);
  int b = Integer.parseInt(args[1]);, b);
" you have entered these values : " +  a  + " and " +  b);
  int area = rectangle.calculate();
  System.out.println(" area of a rectange is  : " + area);
Output of the program is given below:
C:\java>java EnterValuesFromKeyboard 4 5
you have entered these values : 4 and 5
area of a rectange is : 20
Download this example
Post a Comment