Write a class Battery that models a rechargeable battery.
       totalCapacity: double
       availableBattery: double;( this contains battery charge available)
        String company;
·        having no parameter – for setting values to zero or null.
·        having two parameters for assigning values to both data members.
·        Overload the above constructor and use this keyword to set the values of data members
·        Provide getters and setters for data member(s).
·        The method public void drain (double amount) drains the capacity of the battery by the given amount.
·        The method public void charge (double amount) charges the battery by adding amount to availableBattery make sure it’s less  than totalcapacity.
·        A method toString to print object data.
1.     Inside main, create 3 objects.
a.     Set values of first object using constructor.
b.     Take data from user and set the values for the 2 objects and display values.
2.     Call all the above methods (drain, charge) and display updated values.
package battery;
import java.util.Scanner;
public class Battery {
  private double totalCapacity;
   private double availableBattery;
    private String company;
    Â
    public Battery(){
 Â
}
public Battery(double totalCapacity, double availableBattery){
  this.totalCapacity = totalCapacity;
  this.availableBattery = availableBattery;Â
}
  void setTotalCapacity(double n){
    totalCapacity = n;
  }
  Â
  void setAvailableBattery(double t){
    availableBattery = t;
  }
  Â
  double getTotalCapacity(){
    return totalCapacity;
  }
  Â
  double getAvailableBattery(){
    return availableBattery;
  }
  public void charge (double amount){
    availableBattery = availableBattery + amount;
  }
  public void drain (double amount){
    availableBattery = availableBattery - amount;
  }
  public String toString(){
    return "Total Capacity " +String.valueOf(totalCapacity) +"\n Total Capacity "+ String.valueOf(availableBattery);
  }
  public static void main(String[] args) {
    Battery first = new Battery(10,20);
    Â
    Battery second = new Battery();
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the total capacity");
    double total = scan.nextDouble();
    Â
    System.out.println("Enter the available capacity");
    double av = scan.nextDouble();
    Â
    second.setTotalCapacity(total);
    second.setAvailableBattery(av);
    Â
    Â
    System.out.println("Enter the total capacity");
    double total1 = scan.nextDouble();
    Â
    System.out.println("Enter the available capacity");
    double av1 = scan.nextDouble();
    Â
   Â
    Â
    Battery third = new Battery();
    Â
     third.setTotalCapacity(total1);
    third.setAvailableBattery(av1);
    Â
    System.out.println(third.toString());
    Â
    third.charge(10);
    Â
    System.out.println(third.toString());
    Â
    third.drain(5);
    System.out.println(third.toString());
    Â
    Â
  }
  Â
}
Comments
Leave a comment