Java program to calculate telephone bill, here is the detailed program. There are certain steps to be taken so that, we arrive at our desired solution. Our first step is to understand the problem completely and to also see if any constraints are mentioned. Then, we determined the inputs required as well as the expected output. Then, we plan on the logic to reach our expected output.
Our problem statement is, to calculate the telephone bill based on the number of calls. Therefore, our required input here is the number of calls. Our expected output in this problem is, to find the telephone bill. The logic used is mentioned below.
To read inputs at runtime, in Java we can make use of the Scanner class. This can be used to read any primitive datatype by creating an object of this class and invoking the methods. Here, since our input is the number of calls, we make use of the nextDouble() method to do so.
Scanner sc=new Scanner(System.in); //creating object
System.out.println(“enter the no of calls”);
n=sc.nextDouble(); //reading value at runtime
After getting our input, based on the number of calls made (n), the amount charged varies and so does its calculation. But one thing to keep in mind is, irrespective of the number of calls, for the first 100 calls, minimum of 200Rs is to be paid which is stored in a variable (total bill)
If the number of calls made is between 100 and 150 then, for the first 100 its the same 200Rs while, for the next 50 calls, each call costs 0.6Rs. So, the formula used is:
totalbill=totalbill+((n-100)*0.6);
Else, if the number of calls (n) is between 150 to 200 then, till 150 calls its the same as above while, for the next 50 calls i.e., 150th to 200th call, it costs 0.5Rs per call. So, the calculation is as follows:
totalbill=totalbill+((n-100)*0.6+(n-150)*0.5);
Else if the number of calls (n) is greater than 200 then, for all the calls after 200th call, it costs 0.4Rs per call. So, the calculation is as follows:
totalbill=totalbill+((n-100)*0.6+(n-150)*0.5+(n-200)*0.4);
This way, we calculate the total bill based on the number of calls and finally display on our console screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Scanner; class CalculateTelephoneBill { public static void main(String args[]) { double n,totalbill=200; Scanner sc=new Scanner(System.in); System.out.println("enter the no of calls"); n=sc.nextDouble(); if(n>100 &&n<=150) { totalbill=totalbill+((n-100)*0.6); } else if(n>150 && n<=200) { totalbill=totalbill+((n-100)*0.6+(n-150)*0.5); } else if(n>200) { totalbill=totalbill+((n-100)*0.6+(n-150)*0.5+(n-200)*0.4); } System.out.println("total bill is"+totalbill+"rs"); } } |
Output:
1 2 3 |
enter the no of calls 156 total bill is236.6rs |