write a java program for the above question which is given in image
Answers
OOP in Java
Object Oriented Programming in Java focuses on the concept of objects. Here, we are given the task of creating a class named Telephone.
Classes act as blueprint of objects. Objects are created as instances of a class.
Here, the question asks to print both amount and total amount in the display() function. However, the output shown suggests only the total amount to be displayed. So I have gone only for total amount.
Here is the working program, along with a Main class to test the program.
_______________________
class Telephone
{
int prv, pre, call; //Declaring the variables
String name;
double amt, total;
void input(int previousReading, int presentReading, String nameOfCustomer)
{
prv = previousReading; //Initialising the variables
pre = presentReading;
name = nameOfCustomer;
}
void cal()
{
call = pre-prv;
int n = call; //We will work on this variable n
if(n<=100) //Upto 100 calls, no charge
{
amt=0;
}
else if (n<=200)
{
n = n - 100; //n reduced by 100 and multiplied by 90
amt = 90 * n;
}
else if (n <= 400) //Case of 200< n <=400
{
amt = 90 * 100; //First 100 calls cost 90 paise each
n = n - 200; //Reduce n by 200 (because n >200 calls)
amt += n*80; //Adding (n*80) to amt
}
else //Case of n>=400 calls
{
amt = 90*100; //First 100 calls cost 90 paise each
amt += 80*200; //Next 200 calls cost 80 paise each
n = n - 400; //Reducing n by 400
amt += n*70; //Adding (n*70) to amt
}
amt = amt/100; //Converting amt to rupees. Dividing by 100
total = 180 + amt; //Adding monthly rent of INR 180 to get total amount
}
void display() //Display Function
{
/* We use C style formatting command, called System.out.printf()
* This helps us to format strings and integers and reserve specific amount of space for each
* Example: %-25s reserves 25 spaces for a string and aligns it to the left
*/
System.out.printf("%-25s %-15s %-20s","Name of customer","Calls made","Amount to be paid");
System.out.printf("\n%-25s %-15d %-20.2f",name,call,total);
}
}
public class Main //Main Function to test the program
{
public static void main(String[] args)
{
Telephone tlp = new Telephone(); //Creating class object
tlp.input(120,536,"Oshma");
tlp.cal();
tlp.display();
}
}