Call Cost Calculation in Java¶
This program demonstrates a simple calculation of call cost based on duration and rate, and then updates a user's balance. It introduces basic Java concepts such as variable declaration, arithmetic operations, and printing output to the console.
Program Code¶
class CallCostDemo
{
public static void main(String[] args)
{
double bal = 78.5, rate = 0.02;
int secs = 85;
System.out.println("Balance B4 Call: " + bal);
System.out.println("Call Duration: " + secs + " seconds");
System.out.println("Rate per second: " + rate);
double cost = secs * rate;
bal = bal - cost;
System.out.println("Total cost 4 call: " + cost);
System.out.println("Balance after call: " + bal);
}
}
Detailed Explanation¶
class CallCostDemo: This line declares a class namedCallCostDemo. In Java, all code resides within classes.public static void main(String[] args): This is the main method, the entry point of any Java application.public: Makes the method accessible from anywhere.static: Allows themainmethod to be called without creating an object of the class.void: Indicates that the method does not return any value.main: The name of the method.String[] args: An array of strings that can be used to pass command-line arguments to the program.
double bal = 78.5, rate = 0.02;:- Declares two
doubletype variables:bal(for balance) initialized to78.5, andrate(for rate per second) initialized to0.02.doubleis used for floating-point numbers.
- Declares two
int secs = 85;:- Declares an
inttype variablesecs(for duration in seconds) initialized to85.intis used for whole numbers.
- Declares an
System.out.println(...): These lines print information to the console.System.out: Is an object that represents the standard output stream.println(): A method that prints the given argument to the console and then moves the cursor to the next line.- The
+operator concatenates strings and variables.
double cost = secs * rate;:- Calculates the
costof the call by multiplyingsecsbyrate. The result is stored in adoublevariablecost.
- Calculates the
bal = bal - cost;:- Updates the
bal(balance) by subtracting thecostof the call from it.
- Updates the
- Final
System.out.printlnstatements: These print the calculatedcostand thebalafter the call.
Program Output¶
When you compile and run the CallCostDemo program, the output will be:
Balance B4 Call: 78.5
Call Duration: 85 seconds
Rate per second: 0.02
Total cost 4 call: 1.7
Balance after call: 76.8
Flowchart¶
Here's a flowchart illustrating the program's logic:
graph TD
A[Start] --> B[Initialize bal = 78.5, rate = 0.02, secs = 85]
B --> C[Display Initial Balance, Duration, Rate]
C --> D[Calculate cost = secs * rate]
D --> E[Update Balance: bal = bal - cost]
E --> F[Display Total Cost and Final Balance]
F --> G[End]