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