Saturday, 7 September 2013

parameterized constructor in java

class Box{
double width;
double height;
double depth;
//this is the constructor for Box

        Box(double w, double h, double d)
        {
        width = w;
        height = h;
        depth = d;
        }
// compute and return value
        double volume()
        {
        return width*height*depth;
        }
}

    class BoxParConst{
    public static void main(String args[]){
// declare allocate and initialize Box objects

    Box mybox1 = new Box(10,20,15);
    Box mybox2 = new Box(3,6,9);
   
    double vol;
   
// get the volume of first box
   
    vol = mybox1.volume();
    System.out.println("Volume of the first Box is:"+vol);

// get the volume of second box

    vol = mybox2.volume();
    System.out.println("Volume of the second Box is:"+vol);
   
    }
}

Reading a value through key board and printing factorial of a given number

import java.io.*;

class Fact{
    public static void main(String args[]){

    BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
try{

    int fact=1;

        System.out.println("Enter a number to find out factorial of a given number: \n" );
        String nu = Br.readLine();
        int n = Integer.parseInt(nu);

        for(int i=2;i<=n;i++)
        {
            fact=fact*i;   
       
        }
   
            System.out.println("Factorial of a given number is:" +fact);

    }catch (IOException err){
            System.out.println("Error reading line");
            }
       
    }
}