Lab04 in
Lab04 in
CS123
CODE
CLASS CODE
public class Fraction{
private int num;
private int dem;
public Fraction(){
num=0;
dem=0;
}
Screenshot
Explanation
1. Fraction Representation:
The Fraction class represents fractions with numerator and
denominator fields.
Constructors allow for creating fractions with different
initializations.
2. Arithmetic Operations:
Static methods (add, less) handle addition and subtraction of
fractions.
Helper functions (lcm, gcd) assist in calculating the necessary
values.
3. Error Handling:
Error handling prevents division by zero when setting the
denominator.
Invalid inputs trigger an error message and graceful program exit.
4. Demonstration:
The main method showcases fraction creation and arithmetic
operations.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Task 01:
Create a class AreaCalculator
To compute the area of various geometric shapes including squares, rectangles,
circles, triangles, parallelograms, and trapezoids
The class should overload calculateArea methods with different parameters
corresponding to the dimensions of each shape
The program should prompt the user to choose a shape for which the area needs
to be calculated
It should request the necessary inputs (such as side lengths, radius, base, and
height) from the user
Based on the user's choice, the appropriate method from the class should be
invoked to compute the area
CODE
CLASS CODE
import java.lang.Math;
import java.util.Scanner;
public class AreaCalculator {
public int area(int side) {
int area = side * side;
return area;
}
Screenshot
Explanation
Task 03:
Attributes accountNumber and balance
Three overloaded constructors
No argument constructor
Parameterized that takes an accountNumber as a parameter and initializes
balance to 0.0
Parameterized that takes both an accountNumber and balance as parameters
CODE
CLASS CODE
public class Bank{
private int acc;
private int balance;
public Bank(){
this.acc = 123;
this.balance = 0;
}
public Bank(int accountNumber){
this.acc = accountNumber;
this.balance = 0;
}
public Bank(int accountNumber, int balance){
this.acc = accountNumber;
this.balance = balance;
}
public void depositAmount(int amount){
balance+=amount;
System.out.println("New Balance" +balance);
}
public void withdrawAmount(int amount){
if(balance>=amount){
balance-=amount;
System.out.println("Remaining Balance" +balance);
}
else{
System.out.println("Insufficient Balance");
System.out.println("Current Balance" +balance);
}
}
public int getAccountNumber(){
return acc;
}
public int checkBalance(){
return balance;
}
public static void main(){
Bank b1 = new Bank(234);
Bank b2 = new Bank(234,100);
b1.depositAmount(400);
b1.withdrawAmount(200);
b2.depositAmount(400);
b2.withdrawAmount(200);
}
}
Screenshot
Explanation