Advanced Java Programming

 Q1. Write a program to calculate the area of rectangle and triangle using interfaces.

Ans:
import java.util.Scanner;

interface AreaofRec 
{
    abstract void rec(int a, int b);
}

interface AreaofTri 
{
    abstract void tri(int num1, int num2, int num3);
}

public class Rectangle implements AreaofRec, AreaofTri 
{
    public void tri(int num1, int num2, int num3) 
    {
        if (num1 > 0 && num2 > 0 && num3 > 0) {
    if (num1 + num2 > num3 && num2 + num3 > num1 && num1 + num3 > num2) 
        {
            float s = (num1 + num2 + num3) / 2;
            double raw = (s * (s - num1) * (s - num2) * (s - num3));
            double ans = Math.pow(raw, 0.5);
            System.out.println("Area of the Triangle " + ans);
        } }
        else 
        {
            System.out.println("Invalid Dimensions! Enter correct Dimensions ");
        }
    }
    public void rec(int a,int b)
    {
        System.out.println("Area of the Rectangle " + (a * b));
    }
    
    public static void main(String[] args) 
    {
        System.out.println("Enter 1 for Area of Triangle and 2 for Area of Rectangle:- ");
        Scanner input = new Scanner(System.in);
        Rectangle area = new Rectangle();
        int a = input.nextInt();
        if (a == 1) {
            System.out.print("Enter first side of triangle:- ");
            int num1 = input.nextInt();
            System.out.print("Enter second side of triangle:- ");
            int num2 = input.nextInt();
            System.out.print("Enter Third side of triangle:- ");
            int num3 = input.nextInt();
            
            area.tri(num1,num2,num3);

        } 
        else if (a == 2) 
        {
            System.out.print("Enter Length of the rectangle:- ");
            int x = input.nextInt();
            System.out.print("Enter Breadth of the rectangle:- ");
            int y = input.nextInt();
            area.rec(x, y);
        } else {
            System.out.println("Invalid Input");
        }

    }
}


Q2. Design a class named Car in package P1, having registration number, model and engine as its private members. Here engine is an object of a class called Engine in package P2 with the private members: chassis number and make. Define a suitable constructor of Car and override toString() method to print the details of a car. Assume appropriate data types for the instance members of the classes. Write a Java program to test the above class.

Ans:
---------------------------------------------------------------------------------------------------------------------------
package pacakge1;

import pacakge2.*;

public class Car extends Engine 
{

    public int registration_number;
    public String model;
    public Engine engine = new Engine();

    Car(int registration_number, String model, Engine engine2) 
    {
        this.registration_number = registration_number;
        this.model = model;
        engine.chasis_number = engine2.chasis_number;
        engine.make = engine2.make;

    }

    void topString() {
        System.out.println(registration_number);
        System.out.println(model);
        System.out.println(engine.chasis_number);
    }

}

class Show extends Car {

    Show(int registration_number, String model, Engine engine1) {
        super(registration_number, model, engine1);
    }

    void topString() {
        System.out.println(registration_number);
        System.out.println(model);
        System.out.println(engine.chasis_number);
        System.out.println(engine.make);
    }

    public static void main(String[] args) {
        Engine eng = new Engine(28364,"hhuih-f-d-sf");
        Show obj = new Show(234235235, "2HGG532F", eng);
        obj.topString();
    }
}

---------------------------------------------------------------------------------------------------------------------------

package pacakge2;

public class Engine {
    public int chasis_number;
    public String make;

    public Engine(int chasis_number, String make){
        this.chasis_number = chasis_number;
        this.make = make;
    }

    public Engine() {
        chasis_number = 2345245;
        make = "31-43-234";
    }
}


Q3. Define a class Figure in package P1, having dim1 and dim2 as two private members. Inherit two more classes: Rectangle and rightAngledTriangle. Write a Java program (in package P2) to ask the user for the type of shape and then using the concept of dynamic method dispatch, display the area of the appropriate subclass.

Ans:
package P1;
// ye new class hai RightTri.java
public class RightTri extends Figure
{
public void area()
{
System.out.println("Enter base of triangle:");
double b=in.nextDouble();
System.out.print("Enter height of triangle:");
double h=in.nextDouble();
if (b>0 && h>0)
{
Figure f1=new Figure(h,b);
System.out.println("Area of triangle: "+ h*b*0.5);
}
else
System.out.println("Invalid dimensions ");
}
}
------------------------------------------------------------
package P1;
// ye new class hai RightTri.java
public class RightTri extends Figure
{
public void area()
{
System.out.println("Enter base of triangle:");
double b=in.nextDouble();
System.out.print("Enter height of triangle:");
double h=in.nextDouble();
if (b>0 && h>0)
{
Figure f1=new Figure(h,b);
System.out.println("Area of triangle: "+ h*b*0.5);
}
else
System.out.println("Invalid dimensions ");
}
}
-------------------------------------------------------------
package package1;

public class Fig {

    private int dim1;
    int dim2;

    public

    Fig(int a, int b) {
        dim1 = a;
        dim2 = b;
    }

    int d1() {
        return dim1;
    }

    int d2() {
        return dim2;
    }
}

--------------------------------------------------------------------------------------------------------------------------
package package2;

import java.util.Scanner;

import package1.Fig;
import package1.Rectangle;
import package1.Rightangledtriangle;
import package1.Fig.*;

public class driver {
    public static void main(String[] args) {
        System.out.println("enter the dimensions = ");
        Scanner s = new Scanner(System.in);
        int l = s.nextInt();
        int b = s.nextInt();

        System.out.println("enter the value 1  for area rectangle of  and  value 2 for rightangletriangle area= ");
        int op = s.nextInt();
        if (op == 1) {
            Fig r = new Rectangle(l, b);
            ((Rectangle) r).showarea();
        } else {
            Fig rt = new Rightangledtriangle(l, b);
            ((Rectangle) rt).showarea();

        }
    }

}

Q4. Write a program in Java that reads an integer numberOfRows and handles NumberFormatException if any invalid integer is entered by the user. If numberOfRows is negative, then display a message to the user to enter a positive number. If numberOfRows is positive, then display the following pattern (e.g. - numberOfRows in the figure below is 



Ans:

import java.util.InputMismatchException;
import java.util.Scanner;

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

        try 
        {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter the number of Rows you want in the pattern:- ");
            int NumberOfRows = in.nextInt();
            if (NumberOfRows < 0) 
            {
                throw new NumberFormatException();
            }
            for (int i = NumberOfRows; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    System.out.print(" ");
                }
                for (int l = 1; l <= NumberOfRows - i; l++) 
                {
                    System.out.print(l);
                }
                for (int k = NumberOfRows - i + 1; k > 0; k--) 
                {
                    System.out.print(k);
                }
                System.out.println();
            }
        } 
        catch (NumberFormatException numberFormatException) 
        {
            System.out.println("Please! Enter a Positive value for the row");
        } 
        catch (InputMismatchException inputMismatchException) 
        {
            System.out.println("Please! Enter a valid integer value");
        }
    }
}


Q5. Create a class called Fraction that can be used to represent the ratio of two integers. Include appropriate constructors and methods. If the denominator becomes zero, throw and handle an exception.

Ans:
/*Create a class called Fraction that can be used to represent the ratio of two integers. Include
appropriate constructors and methods. If the denominator becomes zero, throw and handle an 
exception.*/

import java.util.InputMismatchException;
import java.util.Scanner;

public class Fraction 
{
    protected int num1, den1;
    
    Fraction() 
    {
        this.num1 = 0;
        this.den1 = 0;
    }

    Fraction(int num1, int den1)
    {
        this.num1 = num1;
        this.den1 = den1;
    }

    Fraction toAdd(Fraction show1, Fraction show2)
    {
        int temp1 = show1.num1;
        int temp2 = show1.den1;
        int temp3 = show2.num1;
        int temp4 = show2.den1;
        int num = (temp1 * temp4) + (temp3 * temp2);
        int den = temp2 * temp4;
        for (int i = num; i > 1; i--) 
        {
            if (num % i == 0 && den % i == 0) 
            {
                num = num / i;
                den = den / i;
            }
        }

        Fraction obj = new Fraction(num, den);
        return obj;
    }

    void toPrint(int val1, int val2) 
    {
        System.out.println("Sum of both number is " + val1 + "/" + val2);
    }

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int numinator1, numinator2, denominator1, denominator2;
        try 
        {
            System.out.println("Enter Numinator of First number");
            numinator1 = input.nextInt();
            System.out.println("Enter Denominator of First number");
            denominator1 = input.nextInt();
            try 
            {
                double done1 = numinator1/denominator1;
            } 
            catch (ArithmeticException arithmeticException) 
            {
                System.out.println("Your Value of denominator is invalid! ");
                System.out.println(" So, your denominator value is assigned to be 1");
                denominator1 = 1;
            }
            System.out.println("Enter Numinator of second number");
            numinator2 = input.nextInt();
            System.out.println("Enter Denominator of second number");
            denominator2 = input.nextInt();
            try 
            {
                double done2 = numinator1/denominator1;
            } 
            catch (ArithmeticException arithmeticException)
            {
                System.out.println("Please! Enter valid value for denominator");
                System.out.println(" So, your denominator value is assigned to be 1");
                denominator2 = 1;
            }
            Fraction number1 = new Fraction(numinator1, denominator1);
            Fraction number2 = new Fraction(numinator2, denominator2);
            Fraction answer = new Fraction();
            Fraction x = answer.toAdd(number1, number2);
            int a = x.num1;
            int b = x.den1;
            x.toPrint(a, b);
        } 
        catch (InputMismatchException a) 
        {
            System.out.println("Please, Enter value in Integer ");
        }
    }
}




        // if (denominator1 == 0 && denominator2 == 0) {
        // System.out.println("Invalid Value of Denominator!");
        // } else {
        // Fraction number1 = new Fraction(numinator1, denominator1);
        // Fraction number2 = new Fraction(numinator2, denominator2);
        // Fraction answer = new Fraction();
        // Fraction x = answer.toAdd(number1, number2);
        // int a = x.num1;
        // int b = x.den1;
        // number1.toPrint(a, b);
        // }

Q6. Write a program to create a frame using AWT. Implement mouseClicked(), mouseEntered() and mouseExited() events such that: a. Size of the frame should be tripled when mouse enters it. b. Frame should reduce to its original size when mouse is clicked in it. c. Close the frame when mouse exits it.

Ans:

import java.awt.*;
import java.awt.event.*;

public class pro6 extends Frame implements MouseListener {
    pro6() {

        Button b = new Button("click me");
        b.setBounds(60, 60, 70, 30);
        add(b);
        b.addMouseListener(this);
        setSize(200, 200);
        setVisible(true);
        setLayout(null);

    }

    public void mouseClicked(MouseEvent e) {
        setSize(200, 200);

    }

    public void mouseEntered(MouseEvent e) {
        setSize(900, 900);
    }

    public void mouseExited(MouseEvent e) {
        dispose();
    }

    public static void main(String[] args) {
        pro6 p = new pro6();
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }
}


Q7. Using AWT, write a program to display a string in frame window with pink color as background.


Ans:
import java.awt.*;
import java.awt.event.*;

public class pro7 extends Frame {

    pro7() {
        Label l = new Label("narayn kumar");
        l.setBounds(90, 80, 180, 30);
        l.setForeground(Color.BLUE);
        add(l);
        setBackground(Color.PINK);
        setSize(1200, 1200);
        setVisible(true);
        setLayout(null);
    }

    public static void main(String[] args) {
        new pro7();
    }

}


Q8. Using AWT, write a program to create two buttons named “Red” and “Blue”. When a button is pressed the background color should be set to the color named by the button’s label.


Ans:
import java.awt.*;
import java.awt.event.*;

public class pro8 extends Frame {

    pro8() {
        Button b1 = new Button("blue");
        Button b2 = new Button("red");
        b1.setBounds(120, 70, 90, 40);
        b2.setBounds(70, 80, 89, 76);
        add(b1);
        add(b2);
        setSize(200, 200);
        setVisible(true);
        setLayout(new FlowLayout());

        b1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                setBackground(Color.BLUE);
            }

        });
        b2.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                setBackground(Color.RED);
            }

        });

    }

    public static void main(String[] args) {
        new pro8();
    }

}

Q9. Using AWT, write a program using appropriate adapter class to display the message (“Typed character is: ”) in the frame window when user types any key.

Ans:
import java.awt.*;
import java.awt.event.*;

public class Question9 extends Frame {
    Question9() {
        Label l = new Label("narayan");
        TextArea t = new TextArea();
        l.setBounds(30, 70, 690, 20);
        t.setBounds(30, 170, 690, 20);
        add(l);
        add(t);
        setSize(800, 500);
        setVisible(true);
        setLayout(new FlowLayout());

        t.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                String s = t.getText();
                l.setText(" typed " + s);
            }

        });
    }

    public static void main(String[] args) {
        Question9 Q = new Question9();
    }

}


Q10. Using AWT, write a program to create two buttons labelled ‘A’ and ‘B’. When button ‘A’ is pressed, it displays your personal information (Name, Course, Roll No, College) and when button ‘B’ is pressed, it displays your CGPA in previous semester.


Ans:
import java.awt.*;
import java.awt.event.*;

public class pro10 extends Frame {
    pro10() {
        Button b1 = new Button("A");
        Button b2 = new Button("b");

        b1.setBounds(170, 60, 80, 30);
        b2.setBounds(80, 60, 80, 30);

        Label l1 = new Label("lable");
        l1.setBounds(70, 180, 390, 70);

        

        add(b1);

        add(b2);

        setSize(500, 300);
        setLayout(null);
        setVisible(true);

        b1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                add(l1);
                l1.setText("Name = narayan kumar course = APS ROll = 2063083");
            }
        });

        b2.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                add(l1);
                l1.setText("CGPA = 9.9");
            }
        });

    }

    public static void main(String[] args) {
        new pro10();
    }

}



Comments